目录
26. Remove Duplicates from Sorted Array
33. Search in Rotated Sorted Array
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路:
A.暴力求解
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int>res;
int len=nums.size();
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
if((nums[i]+nums[j])==target)
{
res.push_back(i);
res.push_back(j);
return res;
}
}
}
return res;
}
};
B.双指针
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> tmp = nums;
int low = 0, hight = tmp.size()-1;
sort(tmp.begin(), tmp.end());
while (low < hight) {
int s = tmp[low]+tmp[hight];
if (s > target)
hight--;
else if (s < target)
low++;
else
break;
}
vector<int> nResult;
for (unsigned int i=0; i<nums.size(); i++) {
if (nums[i] == tmp[low])
nResult.push_back(i);
else if (nums[i] == tmp[hight])
nResult.push_back(i);
}
return nResult;
}
};
C.哈希表
#include<vector>
#include<unordered_map>
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
unordered_map<int, int> m;//创建
vector<int >nResult;
for(int i=0;i<nums.size();i++)
{
m[nums[i]] =i;//键值key
}
for(int i=0;i<nums.size();i++)
{
int tmp = target-nums[i];
if(m.count(tmp) && m[tmp]!=i)//判断是否满足条件
{//主键元素个数 m.count(tmp)
nResult.push_back(i);
nResult.push_back(m[tmp]);
break;
}
}
return nResult;
}
};
对于一上三种方法:
4.Median of Two Sorted Arrays
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
思路一:
想到将两个数组重新 排序,合并之后中间元素则为中位数。归并排序复杂度大于 O(log (m+n)),但是LeetCode 运行通过了[捂脸]
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
int nLen1 = nums1.size();
int nLen2