217. 存在重复元素 - 力扣(LeetCode)
1 2 3 4 5 6 7 8 9 10 11 12
| class Solution { public boolean containsDuplicate(int[] nums) { int n = nums.length; Map<Integer, Integer> map = new HashMap<>(); for (int e : nums) map.put(e, map.getOrDefault(e, 0) + 1); for (Map.Entry<Integer, Integer> entry : map.entrySet()){ int v = entry.getValue(); if (v > 1) return true; } return false; } }
|
349. 两个数组的交集 - 力扣(LeetCode)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for (int e : nums1) set1.add(e); for (int e : nums2) set2.add(e); List<Integer> ans = new ArrayList<>(); for (Integer e : set2){ if (set1.contains(e)){ ans.add(e); } } int[] ret = new int[ans.size()]; for (int i = 0; i < ans.size(); i++) { ret[i] = ans.get(i); } return ret; } }
|
128. 最长连续序列 - 力扣(LeetCode)
这个题如果不用暴力的话我踏马还真想不起来用啥~~~
我做了一遍之后开始不明白为啥就要非得判断if (!set.contains(e - 1))我不能从大向着小判断吗?
- 其实这两个都可以,但是它的目的就是为了寻找连续的那一个极值点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public int longestConsecutive(int[] nums) { Set<Integer> set = new HashSet<>(); for (int e : nums) set.add(e); int ret = 0; for (int e : nums){ if (!set.contains(e - 1)){ int cur_Num = e; int cur_long = 1; while (set.contains(cur_Num + 1)){ cur_Num++; cur_long++; } ret = Math.max(ret, cur_long); } } return ret; } }
|
290. 单词规律 - 力扣(LeetCode)
这个简单题挺难的,也挺怪的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public boolean wordPattern(String pattern, String s) { Map<Character, String> map = new HashMap<>(); String[] v = s.split(" "); int len = pattern.length(); if(len != v.length) return false; for(int i = 0; i < len; i++){ char c = pattern.charAt(i); if(!map.containsKey(c)){ if(map.containsValue(v[i])) return false; map.put(c, v[i]); }else if(!map.get(c).equals(v[i])) return false; } return true; } }
|