Lunski's Clutter

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

0%

287. Find the Duplicate Number

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

There is only one repeated number in nums, return this repeated number.

You must solve the problem without modifying the array nums and uses only constant extra space.

Example 1:

1
2
Input: nums = [1,3,4,2,2]
Output: 2

Example 2:

1
2
Input: nums = [3,1,3,4,2]
Output: 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
TC: O(nlogn) Arrays.sort() is merge sort
SC: O(logn) Java 13's Arrays.sort() uses a dual-pivot quicksort, which uses log n additional space
*/

class Solution {
public int findDuplicate(int[] nums) {
Arrays.sort(nums); // TC: O(nlog(n)) modified mergesort
int len = nums.length;
for (int i = 1; i < len; i++) {
if (nums[i] == nums[i - 1]) {
return nums[i];
}
}

return len;
}

/*
TC: O(n)
SC: O(n)
*/

import java.util.HashSet;

class Solution {
public int findDuplicate(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for(int i=0;i<nums.length;i++){ // O(n)
if(set.contains(nums[i]))
return nums[i]; // contains O(1)
else
set.add(nums[i]); // add O(1)
}
return -1;
}
}

/*
TC: O(n)
SC: O(1)
Floyd Algorithm
*/
class Solution {
public int findDuplicate(int[] nums) {
int slow = 0;
int fast = 0;

do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);

slow = 0;
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}

return slow;
}
}

ref: 142. Linked List Cycle II


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

Welcome to my other publishing channels