classSolution { 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; } };
看過大神後的程式碼
透過讓target和nums相減再觀察是否相減結果還存在於列表內
1 2 3 4 5 6 7 8
classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: ans = [] for i inrange(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