FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-Interview/FindDuplicateNumber.java at master · arjunmullick/coding-Interview · GitHub
arjunmullick
/
coding-Interview
Public
Notifications
You must be signed in to change notification settings
Fork
1
Star
3
Code
Issues
0
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-Interview
/
FindDuplicateNumber.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
62 lines (51 loc) · 1.64 KB
Breadcrumbs
coding-Interview
/
FindDuplicateNumber.java
Copy path
File metadata and controls
62 lines (51 loc) · 1.64 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package
com
.
leetcode
;
import
java
.
util
.
Arrays
;
public
class
FindDuplicateNumber
{
//https://leetcode.com/problems/find-the-duplicate-number/
class
Solution
{
public
int
findDuplicate
(
int
[]
nums
) {
int
n
=
nums
.
length
;
int
l
=
1
;
//[1,n] number to search
int
r
=
n
-
1
;
while
(
l
<=
r
){
int
mid
=
l
+ (
r
-
l
)/
2
;
//mid is potential number not index
int
count
=
count
(
nums
,
mid
);
//no of elements that are < mid
if
(
count
<=
mid
){
l
=
mid
+
1
;
}
else
{
// we have more numbers > mid so look for a number in [l,mid)
r
=
mid
-
1
;
}
}
return
r
+
1
;
}
public
int
count
(
int
[]
nums
,
int
target
){
int
result
=
0
;
for
(
int
n
:
nums
){
if
(
n
<=
target
)
result
++;
}
return
result
;
}
}
}
// note
/*
//binary search on value will not work because number may repeat many time 1,3,3,4,5 or 2,2,3,4,5 so binary search will miss 3 and 2 respectively
// Other test case possible to have 2,2,2,1 or 1,1,2,2 where more than one duplicate in test cases
public int findDuplicate(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
int l = 0;
int r = n-1;
while(l<=r){
int mid = l + (r-l)/2;//index
if(nums[mid] == mid+1){
//search right
l = mid+1;
}else{
r = mid-1;
}
}
return (r>=0)?nums[r+1] : nums[0];
}
*/
Back
|
FazBrowse Home
|
New Git URL