classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: hashset = {} for i in range(len(nums)): if hashset.get(target - nums[i]) isnotNone: return [hashset.get(target-nums[i]),i] hashset[nums[i]] = i
1 2 3 4 5 6 7 8 9 10 11
publicint[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> indexForNum = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (indexForNum.containsKey(target - nums[i])) { returnnewint[]{indexForNum.get(target - nums[i]), i}; } else { indexForNum.put(nums[i], i); } } returnnull; }
publicbooleancontainsDuplicate(int[] nums){ Set<Integer> set = new HashSet<>(); for (int num : nums) { set.add(num); } return set.size() < nums.length; }
classSolution: deffindLHS(self, nums: List[int]) -> int: hashSet = {} for num in nums: hashSet[num] = hashSet.get(num, 0) + 1 long = 0 for i in hashSet: if i + 1in hashSet: long = max(long, hashSet[i] + hashSet[i + 1]) return long
classSolution: deflongestConsecutive(self, nums: List[int]) -> int: hashSet = set(nums) long = 0 for i in hashSet: if i - 1in hashSet: # 判断是不是首个数字 continue curLong = 1 while i + 1in hashSet: curLong += 1 i += 1 long = max(long, curLong) return long
publicintlongestConsecutive(int[] nums){ Map<Integer, Integer> countForNum = new HashMap<>(); for (int num : nums) { countForNum.put(num, 1); } for (int num : nums) { forward(countForNum, num); } return maxCount(countForNum); }
privateintforward(Map<Integer, Integer> countForNum, int num){ if (!countForNum.containsKey(num)) { return0; } int cnt = countForNum.get(num); if (cnt > 1) { return cnt; } cnt = forward(countForNum, num + 1) + 1; countForNum.put(num, cnt); return cnt; }
privateintmaxCount(Map<Integer, Integer> countForNum){ int max = 0; for (int num : countForNum.keySet()) { max = Math.max(max, countForNum.get(num)); } return max; }