LeetCode: 4Sum

一次过

 1 class Solution {

 2  public:

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

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

 5          // DO NOT write int main() function

 6          vector<vector<int>> ret;

 7          if (num.size() < 4) return ret;

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

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

10              if (i > 0 && num[i] == num[i-1]) continue;

11              for (int j = i+1; j < num.size()-2; j++) {

12                  if (j > i+1 && num[j] == num[j-1]) continue;

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

14                  for (int beg = j+1; beg < end; beg++) {

15                      if (beg > j+1 && num[beg] == num[beg-1]) continue;

16                      int sum = num[i] + num[j] + num[beg] + num[end];

17                      if (sum == target) {

18                          vector<int> tmp;

19                          tmp.push_back(num[i]);

20                          tmp.push_back(num[j]);

21                          tmp.push_back(num[beg]);

22                          tmp.push_back(num[end]);

23                          ret.push_back(tmp);

24                      }

25                      else if (sum > target) end--, beg--;

26                  }

27              }

28          }

29          return ret;

30      }

31  };

 下面是C#的代码

 1 public class Solution {

 2     public List<List<int>> FourSum(int[] nums, int target) {

 3         Array.Sort(nums);

 4         List<List<int>> ans = new List<List<int>>();

 5         if (nums.Count() < 4) return ans;

 6         for (int i = 0; i < nums.Count() - 3; i++) {

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

 8             for (int j = i + 1; j < nums.Count() - 2; j++) {

 9                 if (j > i+1 && nums[j] == nums[j-1]) continue;

10                 int left = j+1;

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

12                 while (left < right) {

13                     if (left > j+1 && nums[left] == nums[left-1]) {

14                         left++;

15                         continue;

16                     }

17                     int sum = nums[i] + nums[j] + nums[left] + nums[right];

18                     if (sum == target) {

19                         List<int> tmp = new List<int>();

20                         tmp.Add(nums[i]);

21                         tmp.Add(nums[j]);

22                         tmp.Add(nums[left]);

23                         tmp.Add(nums[right]);

24                         ans.Add(tmp);

25                         left++;

26                     }

27                     else if (sum < target) left++;

28                     else right--;

29                 }

30             }

31         }

32         return ans;

33     }

34 }
View Code

 

你可能感兴趣的:(LeetCode)