此篇文章為我的解題紀錄,程式碼或許並不是很完善

Leetcode - 1. Two Sum

解題思路

使用雙層迴圈來逐步檢查倆倆是否相加結果為target

我滴程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target){
vector<int>ans;
for (int i = 0; i < nums.size(); i++)
{
for(int j = 0; j < i; j++)
{
if (nums[i] + nums[j] == target)
{
ans.push_back(j);
ans.push_back(i);
break;
}
}
}
return ans;
}
};

看過大神後的程式碼

透過讓targetnums相減再觀察是否相減結果還存在於列表內

1
2
3
4
5
6
7
8
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
ans = []
for i in range(len(nums)):
if (target - nums[i]) in nums and i != nums.index(target-nums[i]):
ans.append(i)
ans.append(nums.index(target-nums[i]))
return ans