有效的字母异位词
读完题,首先发现这题是字符串,可以直接转成字符数组用Arrays工具类排下序然后比较一下就可以了。
class Solution {
public boolean isAnagram(String s, String t) {
char[] ch1 = s.toCharArray();
char[] ch2 = t.toCharArray();
Arrays.sort(ch1);
Arrays.sort(ch2);
return Arrays.equals(ch1, ch2);
}
}
然后正常的哈希表的做法如下。
class Solution {
public boolean isAnagram(String s, String t) {
int[] ans = new int[26];
for(int i = 0; i < s.length(); i++) {
ans[s.charAt(i) - 'a']++;
}
for(int i = 0; i < t.length(); i++) {
ans[t.charAt(i) - 'a']--;
}
for(int i = 0; i < 26; i++) {
if (ans[i] != 0) {
return false;
}
}
return true;
}
}
两个数组的交集
也算是比较简单的题目了
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set = new HashSet<>();
HashSet<Integer> res = new HashSet<>();
for(int i = 0; i < nums1.length; i++) {
set.add(nums1[i]);
}
int k = 0;
for(int i = 0; i < nums2.length; i++) {
if (set.contains(nums2[i])) {
res.add(nums2[i]);
}
}
return res.stream().mapToInt(x -> x).toArray();
}
}
快乐数
也是比较简单的一题。 这是我自己的代码。
class Solution {
public boolean isHappy(int n) {
HashSet<Integer> set = new HashSet<>();
int sum = 0;
while (n != 1 ) {
if(set.contains(n)) {
return false;
}
set.add(n);
sum = 0;
while (n > 0) {
int t = n % 10;
sum += t * t;
n = n / 10;
}
n = sum;
}
return n == 1;
}
}
这是卡哥题解的代码,很优雅。
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;
}
}
两数之和
简单题目,做过好多次了。
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
int[] res = new int[2];
for (int i = 0; i < nums.length; i++) {
if(map.containsKey(target - nums[i])) {
res[0] = i;
res[1] = map.get(target - nums[i]);
return res;
}
map.put(nums[i], i);
}
return res;
}
}