力扣热题100——一刷day01"/>
力扣热题100——一刷day01
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、力扣1. 两数之和
- 二、力扣49. 字母异位词分组
- 三、力扣128. 最长连续序列
- 四、力扣283. 移动零
前言
一、力扣1. 两数之和
class Solution {public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> map = new HashMap<>();int[] res = new int[2];for(int i = 0; i < nums.length; i ++){map.put(nums[i], i);}for(int i = 0; i <nums.length; i ++){if(map.containsKey(target-nums[i])){int index = map.get(target-nums[i]);if(index != i){res[0] = i;res[1] = index;break;}}}return res;}
}
二、力扣49. 字母异位词分组
寻找字母易位词的共同点作为哈希表的key
第一种情况对每一个字符串排序,排序结果作为key
class Solution {public List<List<String>> groupAnagrams(String[] strs) {Map<String,List<String>> map = new HashMap<>();for(String str :strs){char[] ch = str.toCharArray();Arrays.sort(ch);String key = new String(ch);List<String> value = map.getOrDefault(key,new ArrayList<>());value.add(str);map.put(key,value);}return new ArrayList<List<String>>(map.values());}
}
第二种对每一个字符串中字母出现的次数计数
class Solution {public List<List<String>> groupAnagrams(String[] strs) {Map<String, List<String>> map = new HashMap<>();for(String str : strs){int[] count = new int[26];for(int i = 0; i < str.length(); i ++){count[str.charAt(i)-'a'] ++;}StringBuilder sb = new StringBuilder();for(int i = 0; i < 26; i ++){if(count[i] != 0){sb.append('a' + i);sb.append(count[i]);}}String key = sb.toString();List<String> list = map.getOrDefault(key, new ArrayList<>());list.add(str);map.put(key,list);}return new ArrayList<List<String>>(map.values());}
}
三、力扣128. 最长连续序列
把数组中的所有数字都放进set中,遍历数组,判断每一个数在set中是否存在,下一个元素,存在说明连续,便让本元素的计数器++,不存在时,取本计数器和res的最大值,其中有一个去重操作,遍历过的元素不要再遍历了,在进入寻找下一个元素之前,先判断set中是否有其前一个元素,若有,说明本元素已被遍历过了,跳过即可,没有,则进入寻找下一个元素的环节
class Solution {public int longestConsecutive(int[] nums) {Set<Integer> set = new HashSet<>();int res = 0;for(int a : nums){set.add(a);}for(int num : set){if(!set.contains(num-1)){int cur = num;int count = 1;while(set.contains(cur+1)){cur ++;count ++;}res = Math.max(res,count);}}return res;}
}
四、力扣283. 移动零
class Solution {public void moveZeroes(int[] nums) {int n = nums.length;for(int i = 0; i < n;){while(i < n && nums[i] != 0){i ++;}if(i == n)return;int j = i + 1;while(j < n && nums[j] == 0){j ++;}if(j == n)return;nums[i] = nums[j];nums[j] = 0;}}
}
更多推荐
力扣热题100——一刷day01
发布评论