diff --git a/leetcode/0167.Two-Sum-II---Input-array-is-sorted/167. Two Sum II - Input array is sorted.go b/leetcode/0167.Two-Sum-II---Input-array-is-sorted/167. Two Sum II - Input array is sorted.go index b73a32e1..e77da7c0 100644 --- a/leetcode/0167.Two-Sum-II---Input-array-is-sorted/167. Two Sum II - Input array is sorted.go +++ b/leetcode/0167.Two-Sum-II---Input-array-is-sorted/167. Two Sum II - Input array is sorted.go @@ -6,13 +6,14 @@ func twoSum167(numbers []int, target int) []int { for i < j { if numbers[i]+numbers[j] == target { return []int{i + 1, j + 1} - } else if numbers[i]+numbers[j] < target { + } + if numbers[i]+numbers[j] < target { i++ } else { j-- } } - return []int{-1, -1} + return nil } // 解法二 不管数组是否有序,空间复杂度比上一种解法要多 O(n) @@ -20,8 +21,8 @@ func twoSum167_1(numbers []int, target int) []int { m := make(map[int]int) for i := 0; i < len(numbers); i++ { another := target - numbers[i] - if _, ok := m[another]; ok { - return []int{m[another] + 1, i + 1} + if idx, ok := m[another]; ok { + return []int{idx + 1, i + 1} } m[numbers[i]] = i } diff --git a/leetcode/0169.Majority-Element/169. Majority Element.go b/leetcode/0169.Majority-Element/169. Majority Element.go index fed696f0..fcc9d507 100644 --- a/leetcode/0169.Majority-Element/169. Majority Element.go +++ b/leetcode/0169.Majority-Element/169. Majority Element.go @@ -6,12 +6,11 @@ func majorityElement(nums []int) int { for i := 0; i < len(nums); i++ { if count == 0 { res, count = nums[i], 1 + } + if nums[i] == res { + count++ } else { - if nums[i] == res { - count++ - } else { - count-- - } + count-- } } return res