#暴力解法 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 9
#哈希表 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 []
Go:
1 2 3 4 5 6 7 8 9 10 11
//暴力解法 functwoSum(nums []int, target int) []int { for i, x := range nums { for j := i + 1; j < len(nums); j++ { if x+nums[j] == target { return []int{i, j} } } } returnnil }
1 2 3 4 5 6 7 8 9 10 11
//哈希表 functwoSum(nums []int, target int) []int { hashTable := map[int]int{} for i, x := range nums { if p, ok := hashTable[target-x]; ok { return []int{p, i} } hashTable[x] = i } returnnil }
//本人解法 import ( "sort" ) funclongestConsecutive(nums []int)int { sort.Ints(nums) mp := make(map[int]int, 0) for _, v := range nums { if _, ok := mp[v-1]; ok { mp[v] = mp[v-1] + 1 delete(mp, v-1) } elseif _, ok := mp[v]; !ok { mp[v] = 1 } } iflen(mp) > 0 { max := 0 for _, v := range mp { if v > max { max = v } } return max } return0 }