242 有效的字母异位词
最简单的想法,排序后比较是否相等
public boolean isAnagram(String s, String t) {
int sLength = s.length();
int tLength = t.length();
if (sLength != tLength) {
return false;
}
s = s.chars()
.sorted()
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
t = t.chars()
.sorted()
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
if (s.equals(t)) {
return true;
}
return false;
}
哈希表法
public boolean isAnagram(String s, String t) {
int sLength = s.length();
int tLength = t.length();
if (sLength != tLength) {
return false;
}
int[] hashMap = new int[26];
for (int i = 0; i < sLength; i++) {
hashMap[s.charAt(i) - 'a']++;
hashMap[t.charAt(i) - 'a']--;
}
for (int i = 0; i < 26; i++) {
if (hashMap[i]!= 0) {
return false;
}
}
return true;
}
349 两个数组的交集
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> resultSet = new HashSet<>();
//遍历数组1
for (int i : nums1) {
set1.add(i);
}
//遍历数组2的过程中判断哈希表中是否存在该元素
for (int i : nums2) {
if (set1.contains(i)) {
resultSet.add(i);
}
}
//将结果几何转为数组
return resultSet.stream().mapToInt(x -> x).toArray();
}
202 快乐数
数字会循环,所以看set中是否存在曾经出现过的数字
private int getNext(int n) {
int totalSum = 0;
while (n > 0) {
int d = n % 10;
n = n / 10;
totalSum += d * d;
}
return totalSum;
}
public boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
n = getNext(n);
}
return n == 1;
}
双指针,判断是否有循环链表 快指针每次比慢指针多走一步,如果有环存在,那么肯定会有相等的时刻
private int getNext(int n) {
int totalSum = 0;
while (n > 0) {
int d = n % 10;
n = n / 10;
totalSum += d * d;
}
return totalSum;
}
public boolean isHappy(int n) {
int slow = n;
int fast = getNext(n);
while (fast != 1 && slow != fast) {
slow = getNext(slow);
fast = getNext(getNext(fast));
}
return fast == 1;
}
1 两数之和
a1 + a2 = target; 在hash表中寻找是否存在a1,使得target - a2 = a1
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> integerMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (integerMap.containsKey(target - nums[i])) {
return new int[]{integerMap.get(target - nums[i]), i};
}
integerMap.put(nums[i], i);
}
return new int[0];
}