242.有效的字母异位词
使用数组模拟哈希表:
- 采用foreach效率会更高一点。
- 数组命名:采用record/hash更具有描述性。
class Solution {
public boolean isAnagram(String s, String t) {
// 边缘条件
if (s.length()!=t.length()) return false;
int[] arr = new int[26];
for(int i=0; i<s.length(); i++){
arr[s.charAt(i) - 'a']++;
arr[t.charAt(i) - 'a']--;
}
for(int i=0; i<26; i++){
if (arr[i]!=0) return false;
}
return true;
}
}
349. 两个数组的交集
检查record[n]
是否为0
:
- 避免遍历数组。
- 去重。
采用stream API
,能够简单地转换为数组。
而直接toArray()
返回的是对象,所以要先转换为int
。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int[] record = new int[1001];
List<Integer> res = new ArrayList<>();
for(int n: nums1){
record[n]++;
}
for(int n: nums2){
if(record[n]!=0){
res.add(n);
record[n] = 0;
}
}
return res.stream().mapToInt(Integer::intValue).toArray();
}
}
202. 快乐数
- 循环判断:n>0
- 写的有点乱,不如随想录有条理。
class Solution {
public boolean isHappy(int n) {
Set<Integer> hash = new HashSet<>();
while(true){
int temp = 0, res = 0;
while(n>0){
temp = n % 10;
res += temp*temp;
n = n/10;
}
if(res==1) return true;
else if(hash.contains(res)) return false;
else hash.add(res);
n = res;
}
}
}
随想录解法:
- 用private方法来求快乐数。
- 判断条件放在while()里,而非while(true)。
class Solution {
public boolean isHappy(int n) {
Set<Integer> record = new HashSet<>();
while (n != 1 && !record.contains(n)) {
record.add(n);
n = getNextNumber(n);
}
return n == 1;
}
private int getNextNumber(int n) {
int res = 0;
while (n > 0) {
int temp = n % 10;
res += temp * temp;
n = n / 10;
}
return res;
}
}
1. 两数之和
- 命名:
int balance = target - nums[i];
- 及时构造数组:
return new int []{i, indexMap.get(balance)};
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hash = new HashMap<>();
int[] res = new int[2];
for(int i=0; i<nums.length; i++){
if(hash.containsKey(target-nums[i])){
res[0] = hash.get(target-nums[i]);
res[1] = i;
return res;
}else{
hash.put(nums[i], i);
}
}
return res;
}
}