class Solution { public boolean isAnagram(String s, String t) { if(s.length()!=t.length()) return false;
int[] res = new int[40]; for(int i=0;i<s.length();i++) { int k=s.charAt(i)-'a'; res[k]++; } for(int i=0;i<t.length();i++) { int k=t.charAt(i)-'a'; res[k]--; } for(int tmp:res) { if(tmp!=0) return false; } return true;
} } |
写这道题目的时候,对哈希表的操作还不熟练,数组就是哈希表,操作数组就容易了很多
class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> res = new HashSet<>(); Set<Integer> res2 = new HashSet<>();
for(int i=0;i<nums1.length;i++) { if(!res.contains(nums1[i])) res.add(nums1[i]); }
for(int i=0;i<nums2.length;i++) { if(res.contains(nums2[i])) res2.add(nums2[i]); } int k=0; int[] result = new int[res2.size()]; for(int tmp:res2) { result[k] = tmp; k++;
} return result; } } |
总是想要遍历哈希表,但其实不需要这么麻烦,这一点还需要灵活一点
class Solution { public boolean isHappy(int n) { Set<Integer> res = new HashSet<>(); while(n!=1&&!res.contains(n)) { res.add(n); n=getnum(n); } if(n==1) return true;
return false; } public int getnum(int n) { int res=0; while(n!=0) { int tmp=n%10; res+=tmp*tmp; n=n/10; } return res; } } |
求和的过程中,sum会重复出现,这对解题很重要!这一点我并不清楚,导致我没有判断循环该何时结束的条件
class Solution { public int[] twoSum(int[] nums, int target) { int[] res = new int[2]; if(nums==null||nums.length==0) { return res; } Map<Integer,Integer> map = new HashMap<>(); int i=0; while(i<nums.length) { int temp = target-nums[i]; if(map.containsKey(temp)) { res[0]=i; res[1]=map.get(temp); return res; } map.put(nums[i],i); i++; }
return res; } } |
开始并没有意识到map和set的区别,导致使用了set却没有办法储存两个值,就用了暴力算法,现在认识到了map和set的区别