两数之和
直接暴力
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
long ans = nums[i]+nums[j];
if(ans>target)continue;
if(ans==target){
return new int[]{i,j};
}
}
}
return null;
}
}
哈希表优化
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer>hm=new HashMap<>();
for(int i=0;i<nums.length;i++){
hm.put(nums[i],i);
}
for(int i=0;i<nums.length;i++){
if(hm.containsKey(target-nums[i])){
int j=hm.get(target-nums[i]);
if(i!=j){
return new int[]{i,j};
}
}
}
return null;
}
}
字母异位词分组
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String str : strs) {
char[] array = str.toCharArray();
Arrays.sort(array);
String key = new String(array);
List<String> list = map.getOrDefault(key, new ArrayList<String>());
list.add(str);
map.put(key, list);
}
return new ArrayList<List<String>>(map.values());
}
}
最长连续序列
class Solution {
public int longestConsecutive(int[] nums) {
Arrays.sort(nums);
int max=0;
HashMap<Integer,Integer>hm=new HashMap<>();
for(int i=0;i<nums.length;i++){
int num=nums[i];
if(hm.containsKey(num))continue;
else{
if(hm.containsKey(num-1)){
hm.put(num,hm.get(num-1)+1);
}else{
hm.put(num,1);
}
}
max=Math.max(max,hm.get(num));
}
return max;
}
}