重点:
- leetcode242:考虑长度不相等的情况,直接返回false。
- leetcode349:set集合转成int数组,直接用迭代器遍历吧。
- leetcode202:检测循环的问题通常可以用到“快慢指针”的思想。
LeetCode242.有效的字母异位词
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length()) {
return false;
}
//用hash存放t字母
Map<Character,Integer> hash = new HashMap<>();
//存放s字母
for(int i=0;i<s.length();i++) {
hash.put(s.charAt(i),hash.getOrDefault(s.charAt(i), 0)+1);
}
//验证t字母
for(int i=0;i<t.length();i++) {
if(!hash.containsKey(t.charAt(i))||hash.get(t.charAt(i))==0) {
return false;
}
hash.put(t.charAt(i), hash.get(t.charAt(i))-1);
}
return true;
}
LeetCode349. 两个数组的交集
public int[] intersection(int[] nums1, int[] nums2) {
//用set集合存放
Set<Integer> set = new HashSet<>();
for(int i=0;i<nums1.length;i++) {
if(!set.contains(nums1[i])) {
set.add(nums1[i]);
}
}
//遍历并将符合值防止到数组中
Set<Integer> set1 = new HashSet<>();
for(int i=0;i<nums2.length;i++) {
if(set.contains(nums2[i])) {
set1.add(nums2[i]);
}
}
// 迭代器遍历set转数组
int[] res = new int[set1.size()];
Iterator<Integer> it = set1.iterator();
int i = 0;
while (it.hasNext()) {
res[i] = it.next();
i++;
}
return res;
}
LeetCode202. 快乐数
/**
* 检测循环问题-》可用到集合或者快慢指针
* @param n
* @return
*/
public boolean isHappy(int n) {
//初始时,fast在slow前一个
int slow = n;
int fast = go(n);
while(fast!=slow&&fast!=1) {
//fast每次走两步
fast=go(fast);
fast=go(fast);
//slow每次走一步
slow=go(slow);
}
return fast==1;
}
/**
* 走向下一个地方
* @param n
* @return
*/
public int go(int n) {
int sum=0;
while(n>0) {
sum=sum+(n%10)*(n%10);
n=n/10;
}
return sum;
}
LeetCode1. 两数之和
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> hash = new HashMap<>();
for(int i=0;i<nums.length;i++) {
if(!hash.containsKey(target-nums[i])) {
hash.put(nums[i], i);
}else {
return new int[] {hash.get(target-nums[i]),i};
}
}
return new int[]{-1,-1};
}