class Solution {
public boolean isAnagram(String s, String t) {
int[] record = new int[26];
if (s.length() != t.length()) {
return false;
}
// 并不需要记住字符a的ASCII,只要求出一个相对数值就可以了
for (int i = 0; i < s.length(); i++) {
record[s.charAt(i) - 'a']++;
}
for (int i = 0; i < t.length(); i++) {
record[t.charAt(i) - 'a']--;
//如果出现 record[t.charAt(i) - 'a'] < 0,则说明t包含一个不在s中的额外字符,返回false
if (record[t.charAt(i) - 'a'] < 0) {
return false;
}
}
return true;
}
}
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
// 输出结果中的每个元素一定是唯一的,也就是说输出的结果的去重的, 同时可以不考虑输出结果的顺序
if (nums1 == null || nums2 == null
|| nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
Set<Integer> setOne = new HashSet<>();
Set<Integer> setTwo = new HashSet<>();
for(int num: nums1) {
setOne.add(num);
}
for (int num : nums2) {
if (setOne.contains(num)) {
setTwo.add(num);
}
}
int[] result = new int[setTwo.size()];
int index = 0;
for (int value : setTwo) {
result[index++] = value;
}
return result;
}
}
解析: ref. Leetcode
class Solution {
public boolean isHappy(int n) {
Set<Integer> hashSet = new HashSet<>();
while (n != 1 && !hashSet.contains(n)) {
hashSet.add(n);
n= getNext(n);
}
return n == 1;
}
public int getNext(int n) {
int sum = 0;
while (n > 0) {
int d = n % 10;
n = n / 10;
sum += d*d;
}
return sum;
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
if (nums == null || nums.length == 0) {
return result;
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int temp = target - nums[i];
if (map.containsKey(temp)) {
result[1] = i;
result[0] = map.get(temp);
}
map.put(nums[i], i);
}
return result;
}
}