代码随想录第六天
242.有效的字母异位词
242. 有效的字母异位词 - 力扣(LeetCode)
采用数组来记录出现的次数,一个++,一个--,如果最后都为0则返回true
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 count : record) {if (count != 0) {return false;}}return true;}
} 349. 两个数组的交集
349. 两个数组的交集 - 力扣(LeetCode)
双指针方法:
class Solution {public int[] intersection(int[] nums1, int[] nums2) {Set<Integer> set = new HashSet<>();Arrays.sort(nums1);Arrays.sort(nums2);int i = 0, j = 0;while (i < nums1.length && j < nums2.length) {if (nums1[i] == nums2[j]) {set.add(nums1[i]);i++;j++;} else if (nums1[i] > nums2[j])j++;elsei++;}int[] res = new int[set.size()];int index = 0;for (int num : set) {res[index++] = num;}return res;}
} HashSet方法:
class Solution {public int[] intersection(int[] nums1, int[] nums2) {Set<Integer> n1 = new HashSet<>();Set<Integer> n2 = new HashSet<>();for (int i : nums1) {n1.add(i);}for (int i : nums2) {if (n1.contains(i))n2.add(i);}int[] res = new int[n2.size()];int i = 0;for (int j : n2) {res[i++] = j;}return res;}
} 202. 快乐数 19:38min
202. 快乐数 - 力扣(LeetCode)
class Solution {public boolean isHappy(int n) {Set<Integer> record = new HashSet<>();while (n != 1) { if (record.contains(n)) {return false;} else {record.add(n);n = getNextNumber(n);}}return true;}public int getNextNumber(int n) {int res = 0;while (n > 0) {int temp = n % 10;res += temp * temp;n = n / 10;}return res;}
} 1. 两数之和
1. 两数之和 - 力扣(LeetCode)
面试变形:Leetcode 01 两数之和 面试变形-CSDN博客
class Solution {public int[] twoSum(int[] nums, int target) {int[] res = new int[2];Map<Integer, Integer> map = new HashMap<>();for (int i = 0; i < nums.length; i++) {int temp = target - nums[i];if (map.containsKey(temp)) {res[0] = i;res[1] = map.get(temp);break;}map.put(nums[i], i);}return res;}
}
