LeetCode 242.有效的字母异味词
答案
class Solution {
public boolean isAnagram(String s, String t) {
int[] arr = new int[26];
for (int i = 0; i < s.length(); i++){
arr[s.charAt(i) - 'a']++;
}
for (int i = 0; i < t.length(); i++){
arr[t.charAt(i) - 'a']--;
}
for (int i = 0; i < 26; i++){
if (arr[i] != 0){
return false;
}
}
return true;
}
}
LeetCode 349.两个数组的交集
答案
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 ||nums2 == null ||nums2.length == 0){
return new int[0];
}
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for (int i = 0; i < nums1.length; i++){
set1.add(nums1[i]);
}
for (int i = 0; i < nums2.length; i++){
if (set1.contains(nums2[i])){
set2.add(nums2[i]);
}
}
int[] arr = new int[set2.size()];
int j = 0;
for (int i : set2){
arr[j++] = i;
}
return arr;
}
}
LeetCode 202.快乐数
编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。
如果 n 是快乐数就返回 True ;不是,则返回 False 。
示例:
输入:19
输出:true
解释:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
答案
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while (!set.contains(n) && n != 1){
set.add(n);
n = getNextNumber(n);
}
if (n == 1){
return true;
} else{
return false;
}
}
private int getNextNumber(int n){
int res = 0;
while (n > 0){
int temp = n % 10;
res += temp * temp;
n = n /10;
}
return res;
}
}
LeetCode 1.两数之和
答案
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<>();
for (int i = 0; i < nums.length; i++){
int temp = target - nums[i];
if (map.containsKey(temp)){
res[0] = i;
res[1] = map.get(temp);
break;
}
map.put(nums[i], i);
}
return res;
}
}