1. 两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
提示:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
只会存在一个有效答案
class Solution {
public int[] twoSum(int[] nums, int target) {
//暴力
// int[] arr=new int[2];
// for(int i=0;i<nums.length;i++){
// int t=target-nums[i];
// for(int j=i+1;j<nums.length;j++){
// if(t==nums[j]){
// arr[0]=i;
// arr[1]=j;
// }
// }
// }
// return arr;
//哈希
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
int[] arr=new int[2];
for(int i=0;i<nums.length;i++){
if(map.containsKey(target-nums[i])){
arr[0]=map.get(target-nums[i]);
arr[1]=i;
break;
}
map.put(nums[i],i);
}
return arr;
// Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
// for (int i = 0; i < nums.length; ++i) {
// if (hashtable.containsKey(target - nums[i])) {
// return new int[]{hashtable.get(target - nums[i]), i};
// }
// hashtable.put(nums[i], i);
// }
// return new int[0];
}
}
49. 字母异位词分组
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]
示例 2:
输入: strs = [""]
输出: [[""]]
示例 3:
输入: strs = ["a"]
输出: [["a"]]
提示:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] 仅包含小写字母
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String ,List<String>> map=new HashMap<>();
for(String s: strs){
int[] count=new int[26];
for(char c : s.toCharArray()){
count[c-'a']++;
}
StringBuilder sb=new StringBuilder();
for(int i=0;i<26;i++){
if(count[i]>0){
sb.append((char)(i+'a'));
sb.append(count[i]);
}
}
String key=sb.toString();
if(!map.containsKey(key)){
map.put(key,new ArrayList<>());
}
map.get(key).add(s);
}
return new ArrayList<>(map.values());
}
}
思路:
找异位词可以转换为找各个单词出现的频次,如果频次相同,那么就是异位词
字符串转为char[],用到方法s.toCharArray();
map.values()返回的是一个list集合
128. 最长连续序列
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
示例 1:
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
示例 2:
输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9
提示:
0 <= nums.length <= 105
-109 <= nums[i] <= 109文章来源:https://uudwc.com/A/qRyE3
class Solution {
public int longestConsecutive(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int maxLength = 0;
for (int num : set) {
if (!set.contains(num - 1)) { // num is the starting point of a consecutive sequence
int currentNum = num;
int currentLength = 1;
while (set.contains(currentNum + 1)) { // continue to find the consecutive sequence
currentNum++;
currentLength++;
}
maxLength = Math.max(maxLength, currentLength);
}
}
return maxLength;
}
}
思路:
可以用hashset保存原来的数据,遍历hashset,找到第一个元素文章来源地址https://uudwc.com/A/qRyE3