Day6
本题元素只涉及26个小写字母,所以选用数组作为哈希表来存储每个字符串中各个字母出现的次数。然后再对比两个数组的元素即可判断是否为有效的
字母异位词。
class Solution {
public boolean isAnagram(String s, String t) {
int sLen = s.length();
int tLen = t.length();
if (sLen != tLen) return false;
int[] sArray = new int[26];
int[] tArray = new int[26];
for (int i = 0; i < sLen; i++) {
sArray[s.charAt(i) - 'a']++;
tArray[t.charAt(i) - 'a']++;
}
for (int i = 0; i <sArray.length; i++) {
if (sArray[i] != tArray[i]) return false;
}
return true;
}
}
用set1存储数组nums1中出现过的数字,再用set2来存储nums2在set1中出现过的数字。最后将set2转换为数组输出即可。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
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]);
}
}
return set2.stream().mapToInt(x -> x).toArray();
}
}
用set来判断是否出现循环,以此来终止程序。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
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]);
}
}
return set2.stream().mapToInt(x -> x).toArray();
}
}
用map存储已经遍历过的数字,循环数组时,查找map中是否有对应的答案 target - nums[i],存在则输出对应下标。
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 new int[]{-1, -1};
}
}