暴力解法:时间/空间复杂度 O(N²),O(1)
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i] + nums[j] == target){
return new int[]{i,j};
}
}
}
return new int[0];
}
}
哈希表解法:时间/空间复杂度 O(N),O(N)
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashRes = new HashMap<Integer, Integer>();
for(int i = 0;i<nums.length;i++){
if(hashRes.containsKey(target - nums[i])){
return new int[]{hashRes.get(target - nums[i]),i};
}
hashRes.put(nums[i],i);
}
return new int[0];
}
}
用排序方法做。
时间复杂度:O(nklogk),空间复杂度:O(nk)。
// getOrDefault(K,defaultValue) - 返回与指定键K关联的值。如果找不到键,则返回defaultValue。
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> res = new HashMap<String, List<String>>();
for(String str : strs){
char[] target = str.toCharArray();
Arrays.sort(target);
String key = new String(target);
List<String> list = res.getOrDefault(key,new ArrayList<String>());
list.add(str);
res.put(key,list);
}
return new ArrayList<List<String>>(res.values());
}
}
class Solution {
public int longestConsecutive(int[] nums) {
// 创建HashSet集合,存储数组中的整数,并且去重
Set<Integer> nums_set = new HashSet<Integer>();
for(int num:nums){
nums_set.add(num);
}
int maxLength = 0;
for(int num : nums_set){
//如果集合中不包含num-1的值,那么说明这个数字可能是连续序列的起点
if(!nums_set.contains(num - 1)) {
int currentNum = num;
int currentLength = 1;
//当集合中包含当前数+1的值时,说明该序列可以继续延申
while(nums_set.contains(currentNum + 1)){
currentNum += 1;
currentLength += 1;
}
//取最长连续序列
maxLength = Math.max(maxLength,currentLength);
}
}
return maxLength;
}
}
class Solution {
public void moveZeroes(int[] nums) {
int left = 0;
int right = 0;
while(right < nums.length){
if(nums[right] != 0){
int n = nums[left];
nums[left] = nums[right];
nums[right] = n;
left++;
}
right++;
}
}
}
看到“左右”想到双链表
class Solution {
public int maxArea(int[] height) {
int areaMax = 0;
int l = 0;
int r = height.length-1;
while(l < r){
areaMax = Math.max(areaMax,Math.min(height[l],height[r])*(r-l));
if(height[l] < height[r]){
l++;
}else{
r--;
}
}
return areaMax;
}
}
“去重”是关键
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for(int i=0; i < nums.length; i++){
if(nums[i]>0){
return res;
}
if(i>0 && nums[i] == nums[i-1]){
continue;
}
int l = i+1;
int r = nums.length - 1;
while(r>l){
if(nums[i] + nums[l] + nums[r]>0){
r--;
}else if(nums[i] + nums[l] + nums[r]<0){
l++;
}else {
List<Integer> list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[l]);
list.add(nums[r]);
res.add(list);
while(r > l && nums[r] == nums[r-1]){
r--;
}
while(r > l && nums[l] == nums[l+1]){
l++;
}
l++;
r--;
}
}
}
return res;
}
}