
1. 两数之和
题目链接
这一题我们转下思路,我们之前是每次固定一个数,向后遍历
这次我们每次固定一个数,向前遍历,我们每次固定的时候说白了就是向前搜寻符合要求的数
比如[1,2,3,4] target = 4
当我们遍历到数字3的时候,我们固定数字3,向前去寻找3-4 = -1的数
每次都是这样,那我们可不可以把之前的值使用哈希表存起来呢,这样我们每次向前找的时候,我们根据想要求的值,可以直接获取到我们要求的值的下标,存在就返回
如果不存在,我们就把数字放入,为后续固定别的数向前遍历提供依据
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> hashMap = new HashMap<>();
for(int i = 0;i < nums.length;i++){
int num = target-nums[i];
if(hashMap.containsKey(num)){
return new int[]{i,hashMap.get(num)};
}
hashMap.put(nums[i],i);
}
return new int[]{-1,-1};
}
}
2. 判断是否为字符重排
题目链接
这一题其实也很简单,我们使用模拟哈希表先遍历一个字符,统计其出现次数
再去遍历另一个字符,看看是不是都出现了,但凡当前字符在之前哈希表遍历的时候没有出现
我们就可以认为其是新的字符,不符合也要求,直接返回false,否则直到遍历完返回true
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++){
char ch = s2.charAt(i);
if(hash[ch-'a'] > 0){
hash[ch-'a']--;
}else{
return false;
}
}
return true;
}
}
3. 存在重复元素I
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. 存在重复元素II
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
TreeMap<Integer,Integer> treeMap = new TreeMap<>();//数值,对应下标
for(int i = 0;i < nums.length;i++){
if(treeMap.containsKey(nums[i])){
int retLength = i-treeMap.get(nums[i]);
if(retLength <= k){
return true;
}
}
treeMap.put(nums[i],i);
}
return false;
}
}
5. 字母异位词分组
题目链接
这一题我们的思路是这样的
我们先把两个字符串转换成数组,然后我们进行排序,再去分别比较就好寻找对应的组进行插入就好
<String --> key值,String[] --> 使用List去拼接>
每次从数组中取出一个字符串,按照字典顺序进行排序
再去哈希表中寻找符合其顺序的key值位置,如果不存在就创建一个,否则直接拼接就好
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String,List<String>> hashMap = new HashMap<>();
for(String str:strs){
char [] ch = str.toCharArray();
Arrays.sort(ch);
String s = new String(ch);
if(!hashMap.containsKey(s)){
//说明还不存在这个key值,需要创建
hashMap.put(s,new ArrayList());
}
hashMap.get(s).add(str);
}
//直接把哈希表全部展开
return new ArrayList(hashMap.values());
}
}
588

被折叠的 条评论
为什么被折叠?



