力扣热题100——一刷day01

编程入门 行业动态 更新时间:2024-10-18 12:31:32

<a href=https://www.elefans.com/category/jswz/34/1672175.html style=力扣热题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

本文发布于:2023-12-05 18:50:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1665009.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:力扣热题

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!