1.两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> hash=new HashMap();
for(int i=0;i<nums.length;i++){
int x =target-nums[i];
if(hash.containsKey(x)){
return new int[]{i,hash.get(x)};
}
hash.put(nums[i],i);
}
return new int[]{-1, -1};
}
}
2.判断是否互为字符重排
题目链接:面试题 01.02. 判定是否互为字符重排 - 力扣(LeetCode)
class Solution {
public boolean CheckPermutation(String s1, String s2) {
if(s1.length()!=s2.length()){
return false;
}
int[] hash=new int[26];
for(int i=0;i<s1.length();i++){
hash[s1.charAt(i)-'a']++;
}
for(int i=0;i<s2.length();i++){
hash[s2.charAt(i)-'a']--;
if(hash[s2.charAt(i)-'a']<0){
return false;
}
}
return true;
}
}
3.存在重复元素Ⅰ
题目链接:217. 存在重复元素 - 力扣(LeetCode)
将数组遍历到哈希表中,一边遍历,一边查看哈希表中是否右该元素,如果存在,则是重复的元素
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> hash=new HashSet<>();
for(int x:nums){
if(hash.contains(x)){
return true;
}
hash.add(x);
}
return false;
}
}
4.存在重复的元素Ⅱ
题目链接:219. 存在重复元素 II - 力扣(LeetCode)
创建一个哈希表,记录数组中的值和下标,都当遍历一个新的元素时,判断哈希表中有没有与之相同的元素,如果有,则判断他们的下标差是否<=k,如果满足条件的话,返回true,否则返回false
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])){
if(i-hash.get(nums[i])<=k){
return true;
}
}
hash.put(nums[i],i);
}
return false;
}
}
5.字母异位词分组
题目链接:49. 字母异位词分组 - 力扣(LeetCode)
定义一个容器,key的类型使String类型,value的类型是定义了一个字符串类型的列表
在遍历的过程中,先将字符串转成字符数组进行排序,判断hash中是否有该类型的分组,如果没有,则在容器中创建该分组,如果存在,将字符串加入到匹配的分组中,最后返回容器中的字符串列表
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>> hash=new HashMap<>();
for(String s:strs){
char[] ch =s.toCharArray();
Arrays.sort(ch);
String k=new String(ch);
if(!hash.containsKey(k)){
hash.put(k,new ArrayList());
}
hash.get(k).add(s);
}
return new ArrayList(hash.values());
}
}
希望对大家有所帮助!!!!!!