1207. 独一无二的出现次数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public boolean uniqueOccurrences(int[] arr) { Map<Integer, Integer> map1 = new HashMap<Integer,Integer>(); Set<Integer> set1 = new HashSet<Integer>(); for(int i = 0;i<arr.length;i++){ int count = map1.getOrDefault(arr[i],0) + 1; map1.put(arr[i],count); }
for(Map.Entry<Integer,Integer> entry:map1.entrySet()){ set1.add(entry.getValue()); }
return map1.size()==set1.size(); } }
|
49. 字母异位词分组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public List<List<String>> groupAnagrams(String[] strs) { Map<String,List<String>> map = new HashMap<String,List<String>>(); for(String str :strs){ char[] chars = str.toCharArray(); Arrays.sort(chars); String kstr = new String(chars); List<String> list = map.getOrDefault(kstr,new ArrayList<String>()); list.add(str); map.put(kstr,list); } return new ArrayList<List<String>>(map.values()); } }
|
128. 最长连续序列
我们要找到一个连续序列的开始 怎么才算是开始? 它的前一个不存在 因此 利用set.contains 检查是否存在 不存在就可以成为开端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public int longestConsecutive(int[] nums) { Set<Integer> set = new HashSet<Integer>(); int curcount; int longest=0; int curnum; for(int n:nums){ set.add(n); } for(int i=0;i<nums.length;i++){ if(!set.contains(nums[i]-1)){ curcount =1; curnum=nums[i]; while(set.contains(curnum+1)){ curcount++; curnum++; } longest = Math.max(longest,curcount); } } return longest; } }
|