Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

448. Find All Numbers Disappeared in an Array

Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.

Example 1:

1
2
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]

Example 2:

1
2
Input: nums = [1,1]
Output: [2]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
TC: O(n), SC: O(n)  
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
// bulid map
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
map.put(nums[i],1);
}
// check
List<Integer> ans=new ArrayList<>();
for(int i=1;i<=nums.length;i++){
if(!map.containsKey(i)){
ans.add(i);
}
}
return ans;
}
}
  • in-place

use - to mark, skip all already marked number
[4,3,2,7,8,2,3,1]

4: mark index 4 to -
[4,3,2,-7,8,2,3,1]

1: mark index 1 to -
[-4,-3,-2,-7,8,2,-3,-1]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
TC: O(n), SC: O(1)

class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
// bulid map
for (int i : nums) {
int index = Math.abs(i);
if (nums[index - 1] > 0) {
nums[index - 1] *= -1;
}
}
// check
List<Integer> res = new ArrayList<Integer>();
for(int i = 0;i < nums.length;i++){
if(nums[i] > 0){
res.add(i+1);
}
}
return res;
}
}

287. Find the Duplicate Number


如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels