classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: n = len(nums) for i inrange(n): for j inrange(i+1, n): if nums[i] + nums[j] == target: return [i, j] return []
哈希表
1 2 3 4 5 6 7 8
classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: hashtable = dict() for i, num inenumerate(nums): if target - num in hashtable: return [hashtable[target - num], i] hashtable[nums[i]] = i return []
时间复杂度$O(N)$,空间复杂度$O(N)$,为哈希表的开销
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public: vector<int> twoSum(vector<int>& nums, int target){ unordered_map<int, int> hashtable; for (int i = 0; i<nums.size(); ++i){ auto it = hashtable.find(target - nums[i]); if(it != hashtable.end()){ return {it->second, i} } hashtable[nums[i]] = i } return []; } };
classSolution { public: void moveZeroes(vector<int>& nums) { int n = nums.size(), left = 0, right =0; while(right < n){ if(nums[right]) { swap(nums[left], num[right]); left++; } right++; } } };
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defmoveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ n = len(nums) left = right = 0 while right < n: if nums[right] != 0: nums[left], nums[right] = nums[right], nums[left] left += 1 right += 1