代码随想录算法Day06-有效字母异位词、两个数组的交集、两数之和
有效字母异位词
- 判断s是不是t的字母异位词,就是判断两个字符串中的不同字母的个数是否相等。最先想到的就是将两个字符串中的字符和字符出现的次数放入map中保存,然后比较两个map是否相等。
- 但是考虑到题目中只包含26个小写字母,所以可以使用数组来存,数组的索引是字母-'a',数组的值是字母出现次数
public boolean isAnagram(String s,String t) {
int[] nums = new int[26];
char[] ch1 = s.toCharArray();
char[] ch2 = c.toCharArray();
for(char c :ch1) {
nums[c - 'a']++;
}
for(char c: ch2) {
nums[c - 'a']--;
}
for(int n : nums) {
if(n != 0) {
return false;
}
}
return true;
}
两个数组的交集
判断两个数组的交集,就是判断前一个数组中的数有没有在第二个数组中出现过。一旦要判断元素有没有出现过,我们就可以想到使用hash结构,hashset或者hashmap,hash结构可以快速判断是否存在,O(1)找到元素所在的位置。
这道题采用hashSet,因为我们只需要存储数组元素的值。
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set = new HashSet<>();
HashSet<Integer> res = new HashSet<>();
for(int n : nums1) {
set.add(n);
}
for(int n : nums2) {
if(set.contains(n)) {
res.add(n);
}
}
return res.stream.mapToInt(Integer::intValue).toArray();
}
两数之和
- 判断数组中是否有和为target的两个数。暴力解法就是两层for循环
- 为了降低时间复杂度,可以考虑哈希表的方法,判断target-nums[i]在之前是否出现过,使用hashMap结构,因为这个不仅需要知道出现没有,还需要知道出现的索引位置是哪里
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<>();
int[] res = new int[2];
for(int i = 0;i < nums.length;i++) {
int n = target - nums[i];
if(map.conntainsKey(n)) {
res[0] = map.get(n);
res[1] = i;
}
map.put(nums[i],i);
}
return res;
}
浙公网安备 33010602011771号