testforvln 发表于 2013-2-3 14:45:15

3Sum Closest

这题的思路和3Sum一样,只是要考虑一下k在j+1之后是不是需要减1,因为不是0而是绝对值最小,所以有点难考虑= = 我就懒得去想直接没-1 汗啊
public class Solution {    public int threeSumClosest(int[] num, int target) {      Arrays.sort(num);      int tempClose = Integer.MAX_VALUE;      int tempsum = Integer.MAX_VALUE;      for (int i = 0; i != num.length; ++i){                        int k = num.length - 1;            for (int j = i + 1; j < k; j++){                while (num + num + num - target > 0 && k > (j+1))                  k--;                int close = Math.abs(num + num + num - target);                if (close < tempClose){                  tempClose = close;                  tempsum = num + num + num;                }                if (k < num.length - 1){                  close = Math.abs(num + num + num - target);                  if (close < tempClose){                        tempClose = close;                        tempsum = num + num + num;                  }                  k++;                }            }      }      return tempsum;            }}
页: [1]
查看完整版本: 3Sum Closest