Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

题解:
最开始想到的还是暴力枚举,但由于昨天复习的数据结构里说到降低时间复杂度,首先我便想到了使用map排序,但调试过程中发现其实里面的元素是有重复的,便放弃了这种想法。后来想到用节点存储值和下标,利用动态数组储存结点并对值进行排序,再定义i,j来分别首尾遍历,若是对应的两个值不等于target,判断大于还是小于,若是大于,j–;小于,i++。
直到找到相等并存入ans动态数组里。
代码:
class Solution {
public:
struct node{
int value;
int index;
};
static int cmp(node a,node b){
return a.value<b.value;
}
vector<int> twoSum(vector<int>& nums, int target) {
vector<node> v;
for(int i=0;i<nums.size();i++){
v.push_back({nums[i],i});
}
sort(v.begin(),v.end(),cmp);
int i=0,j=v.size()-1;
vector<int> ans;
while(i!=j){
if(v[i].value+v[j].value==target){
ans.push_back(v[i].index);
ans.push_back(v[j].index);
break;
}
else if(v[i].value+v[j].value<target){
i++;
}
else j--;
}
return ans;
}
};

因为以前没有再leetcode上做过题,所以不太熟悉leetcode的在线编程方式,费了很多时间,但也学到了很多东西,又是一点点进步呀~ 加油~
在leetcode里cmp函数前面是用static int,标准用法,用bool编译器无法通过。
本文提供了一种解决LeetCode经典问题“两数之和”的高效算法。该算法通过将原始数组转换为带有索引的节点,并利用动态数组进行排序,进而采用双指针策略寻找目标和。这种方法避免了暴力枚举的高时间复杂度。
689

被折叠的 条评论
为什么被折叠?



