242. Valid Anagram
Link: https://leetcode.com/problems/valid-anagram/
Description
Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Approach
- Define a array
record
with size 26, used to record the frequency of letters ins
. - Traverse
t
, reduce the corresponding frequency of each letter inrecord
. - If all the frequency in
record
equals to 0, then t is an anagram.
Solution
class Solution {
public boolean isAnagram(String s, String t) {
int[] record = new int[26];
for (char c: s.toCharArray())
record[c - 'a']++;
for (char c: t.toCharArray())
record[c - 'a']--;
for (int i : record)
if (i != 0)
return false;
return true;
}
}
349. Intersection of Two Arrays
Link: https://leetcode.com/problems/intersection-of-two-arrays/
Description
Given two integer arrays nums1
and nums2
, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
Solution
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
List<Integer> result = new ArrayList<>();
Set<Integer> s1 = new HashSet<>();
for (int n : nums1)
s1.add(n);
for (int n : nums2) {
if (s1.contains(n)) {
s1.remove(n);
result.add(n);
}
}
return result.stream().mapToInt(Integer::intValue).toArray();
}
}
202. Happy Number
Link: https://leetcode.com/problems/happy-number/
Solution
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while (!set.contains(n) && n != 1) {
set.add(n);
int next = 0;
while (n > 0) {
next += (n % 10) * (n % 10);
n = n / 10;
}
n = next;
}
return n == 1;
}
}
1. Two Sum
Link: https://leetcode.com/problems/two-sum/
Description
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Approach
- Initialize a
map
, key is the element ofnums
, value is the index of the element. - Traverse nums:
- If
map
exists a key that the value of the <key, value> pair equals totarget - nums[i]
, return{i, key}
. - Else save
<nums[i], i>
to themap
.
- If
Solution
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i]))
return new int[] {i, map.get(target - nums[i])};
else
map.put(nums[i], i);
}
return null;
}
}