网站名称格式南宁seo多少钱报价
欢迎关注个人主页:逸狼
创造不易,可以点点赞吗~
如有错误,欢迎指出~
1. 两数之和
解法
解法1: 暴力解法O(n^2)
- 先固定其中一个数
- 依次与该数之前的数相加
解法2: 使用哈希表来做优化O(n)
先固定一个数x,再在hash表内找是否存在target - x,如果没有将x放入hash.
代码
class Solution {public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> hash = new HashMap<>();//<nums[i], i>for(int i = 0; i < nums.length; i++){int x = target - nums[i];if(hash.containsKey(x)){return new int[]{i, hash.get(x)};}hash.put(nums[i], i);}//照顾编译器, 以下不会执行return new int[]{-1, -1};}
}
面试题 01.02. 判定是否互为字符重排
解法
使用两个哈希表(数组模拟哈希表,大小为26)统计两个字符串每个字符出现的个数,再判断这两个哈希表是否相等
优化: 只使用一个哈希表, 先将一个字符串放到hash,再遍历另一个字符串,如果遍历完后有字符的数为-1或不为0,返回false; 为0返回true. 时间复杂度: O(n), 空间复杂度: O(26)~O(1)
细节: 如果两个字符串的长度不相等, 直接返回false
代码
class Solution {public boolean CheckPermutation(String s1, String s2) {if(s1.length() != s2.length()) return false;int[] hash = new int[26];//先把s1的信息统计到哈希表内for(int i = 0; i < s1.length(); i++){hash[s1.charAt(i) - 'a']++;}//遍历s2,判断是否可以重排for(int i = 0; i < s2.length(); i++){hash[s2.charAt(i) - 'a']--;if(hash[s2.charAt(i) - 'a'] < 0) return false;}return true;}
}
217. 存在重复元素
解法
从前往后遍历数组,设当前为x,从hash表中是否有数和x相等,如果没有就把x放入hash里
代码
class Solution {public boolean containsDuplicate(int[] nums) {Set<Integer> hash = new HashSet<>();for(int x : nums){if(hash.contains(x)) return true; hash.add(x);}return false;}
}
219. 存在重复元素 II
解法
使用hash<nums[i], i>从前往后遍历数组,设当前数是x, 在hash表中找是否存在x,如果不存在将x和其下标存入hash表中,可以覆盖前面的值
代码
class Solution {public boolean containsNearbyDuplicate(int[] nums, int k) {Map<Integer, Integer> hash = new HashMap<>();for(int i = 0; i < nums.length; i++){if(hash.containsKey(nums[i])){if(i - hash.get(nums[i]) <= k) return true;}hash.put(nums[i], i);}return false;}
}
49. 字母异位词分组
解法
创建hash<String, String[]>,String用来存排好序的字符串,String[]用来存结果数组
从左向右遍历字符串数组,先对字符串进行排序,放入hash表匹配String,符合就加入,不符合就新建String[]
代码
class Solution {public List<List<String>> groupAnagrams(String[] strs) {Map<String, List<String>> hash = new HashMap<>();//1.先把所有的字母异位词分组for(String s : strs){char[] tmp = s.toCharArray();Arrays.sort(tmp);String key = new String(tmp);if(!hash.containsKey(key)){hash.put(key, new ArrayList());}hash.get(key).add(s);}//2.提取结果return new ArrayList(hash.values());}
}