leetcode——TwoSum、3Sum

TwoSum

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.

Example:

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

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

解析:寻找序列中唯一的和为目标数的两个元素,并返回下标。做法一是直接暴力搜索,但是时间效率低下。另一种可行的做法是先将元素排序,然后用两个指针指向头尾,通过改变指针去寻找目标元素。由于需要返回下标,因此可以先用pair存储元素与其初始下标。具体实现代码如下,时间复杂度为O(nlogn):

class Solution {
public:
	static bool cmp(pair& a, pair& b)
	{
		return a.first < b.first;
	}
    vector twoSum(vector& nums, int target) {
        vector v;
        vector >	num;
        int n = nums.size(), j = 0, k = n - 1;
        for(int i=0; i target)	k --;
        	else
        	{
        		v.push_back(num[j].second);
        		v.push_back(num[k].second);
        		break;
        	}
		}
		return v;
    }
};

还有一种实现比较简易,利用map容器存储元素,之后只需要对每个元素nums[i]判断是否存元素target-nums[i]即可,代码如下:

class Solution {
public:
    vector twoSum(vector& nums, int target) {
        vector ans;
        map M;
        int n = nums.size();
        for(int i=0; i 0)
        	{
        		ans.push_back(i);
        		ans.push_back(M[target - nums[i]]-1);
        		break;
			}
		return ans;
    }
};


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.

Note: The solution set must not contain duplicate triplets.

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

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

解析:根据TwoSum可以很容易得到3Sum的解法,排序之后,对每个元素nums[i],在序列nums[i+1]到nums[n-1]中寻找和为0-nums[i]的两个元素。具体代码如下,时间复杂度为O(n^2):

class Solution {
public:
    vector > threeSum(vector& nums) {
        vector > ans;
        int n = nums.size(), m = -1;
        sort(nums.begin(), nums.end());
        for(int i=0; i 0)	k --;
		        	else
		        	{
						while(j+1 < k && nums[j+1]==nums[j])	j ++;
						while(j < k-1 && nums[k-1]==nums[k])	k --;
		        		vector v;
			        	v.push_back(nums[i]);
			        	v.push_back(nums[j]);
			        	v.push_back(nums[k]);
		        		ans.push_back(v);
		        		j ++;
		        		k --;
		        	}
				}
			}
		return ans;
    }
};




你可能感兴趣的:(leetcode——TwoSum、3Sum)