两数之和

解法思路:
解法一:暴力,双重循环
枚举数组中任何一个数x,看数组中是否存在target-x
时间复杂度O(N^2)
空间复杂度O(1)
class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < len; i++) {
for(int j = i+1;j < len;j++){
if(nums[i]+nums[j] == target){
return new int[]{i,j};
}
}
}
return new int[] { -1, -1 };
}
}
解法二:哈希
方法一的时间复杂度主要在寻找target-x,同一个数据被遍历了多次。
因此将以前访问过的数据保存下来,对于每一个x,先判断哈希表中是否存在target-x,如果存在则返回,否则将x放入哈希表中,这样就可以避免x与target-x都是自己。
时间复杂度O(N)
空间复杂度O(N)
class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < len; i++) {
if (map.containsKey(target - nums[i])) {
return new int[] {i, map.get(target - nums[i]) };
}
map.put(nums[i], i);
}
return new int[] { -1, -1 };
}
}
字母异位词分组

解法一:排序+哈希
将str进行排序,如果互为字母异位词的字符串排序后的字符串是一样的,那么可作为key放入map中
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
for(String str : strs){
char[] chars = str.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
List list = map.getOrDefault(key,new ArrayList<String>());
list.add(str);
map.put(key,list);
}
return new ArrayList<>(map.values());
}
}
最长连续序列

解法一:排序+遍历
先将数组排序,然后遍历当前数组,判断当前num[i]与num[i-1]的关系,如果num[i] == num[i-1]+1,那么cnt++,如果num[i] == num[i-1],cnt不变,如果num[i] > num[i-1]+1,那么当前序列结束,判断是不是最长的即可。
注意:最后还要判断一下cnt是不是最终答案,因为有可能序列为[1,2,3,4]这种导致cnt一直++但是没有和ans判断大小。
时间复杂度:主要是在排序,最好情况O(NlogN)
空间复杂度:O(N)
class Solution {
public int longestConsecutive(int[] nums) {
int len = nums.length;
if (len <= 1) return len;
int ans = 1, cnt = 1;
Arrays.sort(nums);
for (int i = 1; i < len; i++) {
if (nums[i] == nums[i - 1]) {
continue;
}
if (nums[i] == nums[i - 1] + 1) {
cnt++;
continue;
}
ans = Math.max(ans, cnt);
cnt = 1;
}
ans = Math.max(ans, cnt);
return ans;
}
}
解法二:哈希set
先将所有数据存入set,这里时间复杂度为O(N)
其次循环当前数字num,判断数组中是否存在num-1,如果存在则跳过,否则从num开始计算判断num++是否存在
跳过目的:从一个连续序列的最小那个数算起走,避免重复计算
比如:[3,1,2,4],如果我们不跳过,那么num=3时,我们会遍历到[4],num=1时,我们会遍历到[2,3,4],num=2时,我们会遍历到[3,4],那么[3,4]就被遍历了多次
时间复杂度:O(N),内层while循环总共只会将数组中的数字遍历一遍
空间复杂度:O(N)
class Solution {
public int longestConsecutive(int[] nums) {
int ans = 0;
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
for (int num : nums) {
if (set.contains(num - 1)) {
continue;
}
int cnt = 1, t = num;
while (set.contains(++t)) {
cnt++;
}
ans = Math.max(ans, cnt);
}
return ans;
}
}