老姐让我刷刷leetcode的题,今天是第一天,刷了道贼简单的题!
通过第一次的题也大概知道了leetcode的写题方式,不用头文件,库文件各种东西它只给你一个函数/方法, 把这个题的解决方法写入这个函数/方法即可,而且支持vim模式下的编辑,真的很方便
-
1
2
3
4
5Given 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:
1
2
3
4Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Mycode:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
int l=nums.size();
bool flag=false;
for(int i=0;i<l-1;i++){
ans.push_back(i);
for(int j=i+1;j<l;j++){
if (nums[i]+nums[j]==target){
ans.push_back(j);
flag=true;
}
}
if (flag) break;
else ans.clear();
}
return ans;
}
};