1. 两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那两个整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。你可以按任意顺序返回答案。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n=nums.size();
for(int temp=0; temp<n; ++temp){
for(int i=temp+1;i < n;++i){
if(nums[temp]+nums[i] == target){
return {temp, i};
}
}
}
return {};
}
};
时间复杂度:O(n*n);
空间复杂度:O(1);
2. 最接近的三数之和
给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数,使它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在恰好一个解。
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int n = nums.size();
int sum = nums[0]+nums[1]+nums[2];
sort(nums.begin(),nums.end());
for(int i=0; i<n-2; ++i){
int start = i+1, end = n-1;
while(start<end){
int temp = nums[i]+nums[start]+nums[end];
if(abs(temp - target)<abs(sum - target)){
sum = temp;
}
if(temp<target){
++start;
}else if(temp>target){
--end;
}else{
return sum;
}
}
}
return sum;
}
};
时间复杂度:排序O(nlogn)+循环双指针O(n*n);
空间复杂度:排序O(logn);
3. 删除有序数组中的重复项
给你一个升序排列的数组 nums ,请你原地删除重复出现的元素,使每个元素只出现一次 ,返回删除后数组的新长度。元素的相对顺序应该保持 一致 。由于在某些语言中不能改变数组的长度,所以必须将结果放在数组nums的第一部分。更规范地说,如果在删除重复项之后有 k 个元素,那么 nums 的前 k 个元素应该保存最终结果。将最终结果插入 nums 的前 k 个位置后返回 k 。不要使用额外的空间,你必须在 原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
if(n==0){//空数组的情况
return 0;
}
int fast=1, slow=1;
//slow指向没有重复项的新数组的尾部,fast用来判断重复项的结束
while(fast<n){
if(nums[fast] != nums[fast-1]){
nums[slow] = nums[fast];
++slow;
}
++fast;
}
return slow;
}
};
时间复杂度:O(n);
空间复杂度:O(1);
4. 移除元素
给你一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,并返回移除后数组的新长度。不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并原地修改输入数组。元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int n = nums.size();
if(n==0){
return 0;
}
int fast=0, slow=0;
while(fast<n){
if(nums[fast]!=val){
nums[slow]=nums[fast];
++slow;
}
++fast;
}
return slow;
}
};
时间复杂度:O(n);
空间复杂度:O(1);
5. 三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。注意:答案中不可以包含重复的三元组。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
if(n<3){
return {};
}
vector<vector<int>> three;
sort(nums.begin(), nums.end());
if(nums[0]>0){
return {};
}
int i=0;
while(i<n-2){
if(nums[i]>0){//判断,减少循环
break;
}
int start=i+1, end=n-1;
while(start<end){
if(nums[start]+nums[end]>0-nums[i]){
--end;
}else if(nums[start]+nums[end]<0-nums[i]){
++start;
}else{
three.push_back({nums[i], nums[start], nums[end]});
while(start<end && nums[start]==nums[start+1]){
++start;
}//排除start重复的情况
while(start<end && nums[end]==nums[end-1]){
--end;
}//排除end重复的情况
++start;
--end;
}//else
}//while(start<end)
while(i+1<n && nums[i]==nums[i+1]){
++i;
}
++i;
}//while(i<n-2)
return three;
}
};
时间复杂度:O(n*n);
空间复杂度:O(logn);