LeeCode: 3Sum Closest

一次过

 1 class Solution {

 2  public:

 3      int threeSumClosest(vector<int> &num, int target) {

 4          // Start typing your C/C++ solution below

 5          // DO NOT write int main() function

 6          int maxgap = INT_MAX;

 7          int maxclose;

 8          sort(num.begin(), num.end());

 9          for (int i = 0; i < num.size()-2; i++) {

10              int beg = i+1;

11              int end = num.size()-1;

12              while (beg < end) {

13                  int sum = num[i] + num[beg] + num[end];

14                  if (sum == target) return target;

15                  if (abs(sum - target) < maxgap) {

16                      maxgap = abs(sum - target);

17                      maxclose = sum;

18                  }

19                  if (sum < target) beg++;

20                  else end--;

21              }

22          }

23          return maxclose;

24      }

25  };

 下面是C#的代码

 1 public class Solution {

 2     public int ThreeSumClosest(int[] nums, int target) {

 3         Array.Sort(nums);

 4         int ans = nums[0] + nums[1] + nums[2];

 5         for (int i = 0; i < nums.Count(); i++) {

 6             if (i > 0 && nums[i] == nums[i-1]) continue;

 7             int left = i + 1;

 8             int right = nums.Count() - 1;

 9             while (left < right) {

10                 if (left > i + 1 && nums[left] == nums[left-1]) {

11                     left++;

12                     continue;

13                 }

14                 int sum = nums[i] + nums[left] + nums[right];

15                 if (sum == target) return sum;

16                 if (Math.Abs(sum - target) < Math.Abs(ans - target)) ans = sum;

17                 if (sum < target) left++;

18                 else right--;

19             }

20         }

21         return ans;

22     }

23 }
View Code

 

你可能感兴趣的:(close)