练习一 : 两数之和

java
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> hash = new HashMap<>();
hash.put(nums[0],0);
for(int i = 0;i<nums.length;i++){
int x = target-nums[i];
if(hash.containsKey(x)&&hash.get(x)!=i){
return new int[] {i,hash.get(x)};
}
hash.put(nums[i],i);
}
return new int[] {-1,-1};
}
}
练习二 : 存在重复元素

java
class Solution {
public boolean containsDuplicate(int[] nums) {
Map<Integer,Integer> hash = new HashMap<>();
for(int i = 0;i<nums.length;i++){
if(hash.containsKey(nums[i])){
return true;
}
hash.put(nums[i],1);
}
return false;
}
}
练习三 : 存在重复元素 2

java
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer,Integer> hash = new HashMap<>();
for(int i = 0;i<nums.length;i++){
if(hash.containsKey(nums[i])){
int j = hash.get(nums[i]);
if(Math.abs(j-i)<=k){
return true;
}
}
hash.put(nums[i],i);
}
return false;
}
}
练习四 : 字母异位词分组
java
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>> hash = new HashMap<>();
for(int i = 0;i<strs.length;i++){
char[] ch = strs[i].toCharArray();
Arrays.sort(ch);
String tmp = new String(ch);
if(!hash.containsKey(tmp)){
hash.put(tmp,new ArrayList<String>());
}
hash.get(tmp).add(strs[i]);
}
return new ArrayList<>(hash.values());
}
}