1. Two Sum&&15. 3Sum&&18. 4Sum

题目:

1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

15.3Sum:

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

18. 4Sum

Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

思路:

  这三道题本质上属于同一问题:给定一个数组和目标target,求k个元素,使得k个元素相加的和为target。可能出现的变式为:1.求元素的下标;2.不得重复使用同一元素等,下面进行分析。

  对于2Sum而言,要求a+b=target,也就是任意选定元素a,寻找数组中是否有元素b使得b=target-a。可以选择方法有:

    方法一:枚举所有的2-subset, 那么这样的复杂度就是从N选出2个,复杂度是O(N^2)

    方法二:对数组进行排序并利用头尾两个指针找到两个数使得他们的和等于target。

  对于3Sum而言,要求a+b+c=target,这道题可以转化为2Sum问题。即任意选定元素a,在剩余的元素中查找是否存在2个数使得b+c=targe-a。

  对于4Sum而言,也可以转化为2Sum问题。任意选定元素a和b,在剩余的元素中查找是否存在2个数使得c+d=targe-a-b。

 

代码:

2Sum:

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         int l = 0;
 5         int r = nums.size() - 1;
 6         int i = 0;
 7         vector<int> result;
 8         multimap<int, int> m;
 9         multimap<int, int>::iterator itmulti;
10         for (vector<int>::iterator it = nums.begin(); it != nums.end(); it++) {
11             int temp = *it;
12             m.insert(make_pair(temp, i++));
13         }
14         sort(nums.begin(), nums.end());
15         while (l < r) {
16             if (nums[l] + nums[r] == target) {
17                 if (nums[l] == nums[r]) {
18                     for (itmulti = m.equal_range(nums[l]).first;
19                             itmulti != m.equal_range(nums[l]).second;
20                             itmulti++) {
21                         result.push_back((*itmulti).second);
22                     }
23                 } else {
24                     itmulti = m.equal_range(nums[l]).first;
25                     result.push_back((*itmulti).second);
26                     itmulti = m.equal_range(nums[r]).first;
27                     result.push_back((*itmulti).second);
28                 }
29                 break;
30             } else if (nums[l] + nums[r] < target) {
31                 l++;
32             } else {
33                 r--;
34             }
35         }
36         return result;
37     }
38 };

3Sum:

 1 class Solution {
 2 public:
 3     vector<vector<int> > threeSum(vector<int>& nums) {
 4         sort(nums.begin(), nums.end());
 5         vector<vector<int> > results;
 6         for (int i = 0; i < (signed) nums.size() - 2; i++) {
 7             if (i > 0 && nums[i] == nums[i - 1])
 8                 continue;
 9
10             int l = i + 1;
11             int r = nums.size() - 1;
12             while (l < r) {
13                 if (nums[l] + nums[r] + nums[i] < 0) {
14                     l++;
15                 } else if (nums[l] + nums[r] + nums[i] > 0) {
16                     r--;
17                 } else {
18                     vector<int> result;
19                     result.push_back(nums[i]);
20                     result.push_back(nums[l]);
21                     result.push_back(nums[r]);
22                     results.push_back(result);
23                     while (l < r && nums[l] == nums[l + 1]) {
24                         l++;
25                     }
26                     while (l < r && nums[r] == nums[r - 1]) {
27                         r--;
28                     }
29                     l++;
30                     r--;
31                 }
32             }
33         }
34         return results;
35     }
36 };

4Sum:

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         int l = 0;
 5         int r = nums.size() - 1;
 6         int i = 0;
 7         vector<int> result;
 8         multimap<int, int> m;
 9         multimap<int, int>::iterator itmulti;
10         for (vector<int>::iterator it = nums.begin(); it != nums.end(); it++) {
11             int temp = *it;
12             m.insert(make_pair(temp, i++));
13         }
14         sort(nums.begin(), nums.end());
15         while (l < r) {
16             if (nums[l] + nums[r] == target) {
17                 if (nums[l] == nums[r]) {
18                     for (itmulti = m.equal_range(nums[l]).first;
19                             itmulti != m.equal_range(nums[l]).second;
20                             itmulti++) {
21                         result.push_back((*itmulti).second);
22                     }
23                 } else {
24                     itmulti = m.equal_range(nums[l]).first;
25                     result.push_back((*itmulti).second);
26                     itmulti = m.equal_range(nums[r]).first;
27                     result.push_back((*itmulti).second);
28                 }
29                 break;
30             } else if (nums[l] + nums[r] < target) {
31                 l++;
32             } else {
33                 r--;
34             }
35         }
36         return result;
37     }
38 };

时间: 2024-10-05 00:28:44

1. Two Sum&&15. 3Sum&&18. 4Sum的相关文章

[LeetCode] K sum(2Sum、3Sum、4Sum)

1 2Sum Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please not

leetcode 3Sum 3Sum Closest 4Sum

这几个题很典型也是国外一些知名公司经常会问到的题 3Sum: 排序,避免重复,时间复杂度O(n^2) class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { int len=num.size(); sort(num.begin(),num.begin()+len); vector<vector<int> > ret; ret.clear(); i

LeetCode 18 4Sum(4个数的和)

翻译 给定一个有n个数字的数组S,在S中是否存在元素a,b,c和d的和恰好满足a + b + c + d = target. 找出数组中所有的不想等的这四个元素,其和等于target. 备注: 在(a,b,c,d)中的元素必须从小到大排列.(a ≤ b ≤ c ≤ d) 其结果必须不能够重复. 例如,给定S = {1 0 -1 0 -2 2},target = 0. 一个结果集为: (-1, 0, 0, 1) (-2, -1, 1, 2) (-2, 0, 0, 2) 原文 Given an ar

Leetcode之15. 3Sum (medium)

15. 3Sum (medium) 描述 Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example

18. 4Sum(js)

18. 4Sum Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: The solution set must not cont

15 Jun 18 复习, shutil模块

15 Jun 18 复习shutil模块(高级的文件.文件夹.压缩包 处理模块) shutil.copyfileobj(fsrc, fdst[, length])  #将文件内容拷贝到另一个文件中 import shutil shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w')) shutil.copyfile(src, dst)  # 拷贝文件 import shutil shutil.copyfile('f1.log', '

2sum、3sum、4sum以及任意连续的数的和为sum、任意连续或者不连续的数的和为sum

2sum 如果数组是无序的,先排序(n*logn),然后用两个指针i,j,各自指向数组的首尾两端,令i=0,j=n-1,然后i++,j--,逐次判断a[i]+a[j]?=sum,如果某一刻a[i]+a[j]>sum,则要想办法让sum 的值减小,所以此刻i 不动,j--,如果某一刻a[i]+a[j]<sum,则要想办法让sum 的值增大,所以此刻i++,j 不动.所以,数组无序的时候,时间复杂度最终为O(n*logn+n)=O(n*logn),若原数组是有序的,则不需要事先的排序,直接O(n)

18. 4Sum; combination sum

18. 4Sumclass Solution(object): def fourSum(self, nums, target): nums.sort() results = [] self.findNsum(nums, target, 4, [], results) return results def findNsum(self, nums, target, N, result, results): if len(nums) < N or N < 2: return # solve 2-su

18. 4Sum

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: The solution set must not contain duplicate quadruplets. For exampl