提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、力扣242. 有效的字母异位词
- 二、力扣349. 两个数组的交集
- 三、力扣202. 快乐数
- 四、力扣1两数之和
前言
一、力扣242. 有效的字母异位词
class Solution {public boolean isAnagram(String s, String t) {int[] arr = new int[27];for(int i = 0; i < s.length(); i ++){arr[s.charAt(i) - 'a'] ++;}for(int i = 0; i< t.length(); i ++){arr[t.charAt(i) - 'a'] --;}for(int i = 0; i< arr.length; i ++){if(arr[i] != 0){return false;}}return true;}
}
二、力扣349. 两个数组的交集
class Solution {public int[] intersection(int[] nums1, int[] nums2) {Set<Integer> s1 = new HashSet<>();Set<Integer> s2 = new HashSet<>();for(int i = 0; i < nums1.length; i ++){s1.add(nums1[i]);}for(int i = 0; i < nums2.length; i ++){if(s1.contains(nums2[i])){s2.add(nums2[i]);}}int[] arr = new int[s2.size()];int j = 0;for(int i : s2){arr[j++] = i;}return arr;}
}
stream流写法
class Solution {public int[] intersection(int[] nums1, int[] nums2) {Set<Integer> s1 = new HashSet<>();Set<Integer> s2 = new HashSet<>();for(int i = 0; i < nums1.length; i ++){s1.add(nums1[i]);}for(int i = 0; i < nums2.length; i ++){if(s1.contains(nums2[i])){s2.add(nums2[i]);}}return s2.stream().mapToInt(x -> x).toArray();}
}
三、力扣202. 快乐数
class Solution {public boolean isHappy(int n) {Set<Integer> s = new HashSet<>();while(n != 1 && !s.contains(n)){s.add(n);n = fun(n);}return n == 1;}public int fun(int n){int res = 0;while(n > 0){int temp = n % 10;res += temp * temp;n /= 10;}return res;}
}
四、力扣1两数之和
class Solution {public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> map = new HashMap<>();int[] res = new int[2];for(int i = 0; i < nums.length; i ++){map.put(nums[i], i);}for(int i = 0; i < nums.length; i ++){int temp = target - nums[i];if(map.containsKey(temp) && i != map.get(temp)){res[0] = i;res[1] = map.get(temp);break;}}return res;}
}