2020.7.13
350. 两个数组的交集 II
哈希表
public class Solution { public int[] intersect(int[] nums1, int[] nums2) { if(nums1.length > nums2.length) return intersect(nums2, nums1); if(nums1.length <= 0) return new int[0]; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int num : nums1){ int count = map.getOrDefault(num, 0) + 1; map.put(num, count); } int[] result = new int[nums1.length]; int index = 0; for(int num : nums2){ int count = map.getOrDefault(num, 0); if (count > 0) { result[index++] = num; if(--count > 0){ map.put(num, count); }else { map.remove(num); } } } return Arrays.copyOfRange(result, 0 , index); } }
from typing import List from collections import Counter class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: if len(nums1) > len(nums2): return self.intersect(nums2, nums1) if len(nums1) <= 0: return [] ct1 = Counter(nums1) res = list() for num in nums2: count = ct1.get(num, 0) if count > 0: res.append(num) ct1[num] -= 1 if count <= 0: ct1.pop(num) return res nums1 = [1, 2, 2, 1] nums2 = [2, 2] s = Solution() print(s.intersect(nums1, nums2))
7. 整数反转
class Solution { public int reverse(int x) { int flag = 1; long xx = x; if(x < 0) { flag = -1; xx *= flag; } String str = String.valueOf(xx); StringBuffer stb = new StringBuffer(str.length()); for (int i = str.length() - 1; i >= 0 ; i--) { stb.append(str.charAt(i)); } long y = Long.parseLong(stb.toString()); if(y > Integer.MAX_VALUE || y * flag < Integer.MIN_VALUE ) flag = 0; return (int)(flag * y); } }
class Solution: def reverse(self, x: int) -> int: flag = 1 if x < 0: flag = -1 x *= flag y = str(x)[::-1] res = int(y) if (-2)**31 > res * flag or flag * res > 2**31-1: flag = 0 return flag * res