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<int, int>& a, pair<int, int>& b)
{
return a.first < b.first;
}
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> v;
vector<pair<int, int> > num;
int n = nums.size(), j = 0, k = n - 1;
for(int i=0; i<n; i++)
num.push_back(make_pair(nums[i], i));
sort(num.begin(), num.end(), cmp);
while(j < k)
{
if(num[j].first + num[k].first < target) j ++;
else if(num[j].first + num[k].first > 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<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
map<int, int> M;
int n = nums.size();
for(int i=0; i<n; i++)
M[nums[i]] = i+1;
for(int i=0; i<n; i++)
if(M[target - nums[i]] != i+1 && M[target - nums[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 a, b, c 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] ]
class Solution {
public:
vector<vector<int> > threeSum(vector<int>& nums) {
vector<vector<int> > ans;
int n = nums.size(), m = -1;
sort(nums.begin(), nums.end());
for(int i=0; i<n; i++)
if(i == 0 || nums[i] != nums[i-1])
{
int j = i + 1, k = n - 1;
while(j < k)
{
if(nums[i] + nums[j] + nums[k] < 0) j ++;
else if(nums[i] + nums[j] + nums[k] > 0) k --;
else
{
while(j+1 < k && nums[j+1]==nums[j]) j ++;
while(j < k-1 && nums[k-1]==nums[k]) k --;
vector<int> v;
v.push_back(nums[i]);
v.push_back(nums[j]);
v.push_back(nums[k]);
ans.push_back(v);
j ++;
k --;
}
}
}
return ans;
}
};