尽力独立思考找到方法。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> ret, temp, former = nums;
int size = nums.size();
sort(former.begin(), former.end());
for(int i = 0; i < size; i++)
{
for(int j = i + 1; j < size; j++)
{
int flag = former[i] + former[j] - target;
if(flag == 0)
{
temp.push_back(former[i]);
temp.push_back(former[j]);
goto finded;
}
else if(flag > 0)
break;
}
}
finded:
for(int i = 0; i < size; i++)
{
if(nums[i] == temp[0] || nums[i] == temp[1])
ret.push_back(i);
}
return ret;
}
};
在结果上,上面方法比采用hash更快,所需内存更少。
如果有更好的方法,希望不吝赐教!