242.有效的字母异位词
create Arraylist to store String, 比较里面的element,s++,i--,判断条件,如果最后只有0,就是对的。
349两个数组的交集
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
// Create a HashSet to store unique elements from nums1
Set<Integer> set = new HashSet<>();
for (int num : nums1) {
set.add(num);
}
// Create a List to store the intersection elements
List<Integer> intersection = new ArrayList<>();
for (int num : nums2) {
if (set.contains(num)) {
intersection.add(num);
set.remove(num); // Remove the element from the set to avoid duplicates
}
}
// Convert the List to an array
int[] result = new int[intersection.size()];
for (int i = 0; i < intersection.size(); i++) {
result[i] = intersection.get(i);
}
return result;
}
}
//O(m + n)
202
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while (n != 1) {
if (set.contains(n)) {
return false;
}
set.add(n);
n = calculateSquareSum(n);
}
return true;
}
private int calculateSquareSum(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
}
If n is already in the set, return false (number is not happy).
Add n to the set.
Calculate the sum of the squares of the digits of n.
Set n to be the sum calculated in the previous step.