Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit34b15ba

Browse files
Merge pull requestneetcode-gh#3067 from viet2307/java/leetcode-0540
Create 0540-single-element-in-a-sorted-array.java
2 parents5d3baf8 +de21d0b commit34b15ba

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
* Time complexity: O(n)
3+
* Space complexity: O(1)
4+
*/
5+
6+
classSolution {
7+
publicintsingleNonDuplicate(int[]nums) {
8+
intn =nums.length;
9+
intleft =0,right =n-1;
10+
11+
// if nums only has one element
12+
if(n <2)returnnums[0];
13+
14+
// if the answer lies at either end of the array
15+
if(nums[left+1] !=nums[left])returnnums[left];
16+
if(nums[right-1] !=nums[right])returnnums[right];
17+
18+
// when you see requirement of O(log n) time and O(1) space
19+
// most of the time you gonna need binary search
20+
// either that or some hacky method using math or bitwise
21+
while(left <right) {
22+
intmid =left + (right-left)/2;
23+
intcurr =nums[mid];
24+
// we already check either end so mid will never gonna be out of array's bound
25+
intprev =nums[mid-1];
26+
intnext =nums[mid+1];
27+
28+
// if mid lands on the result, just return it
29+
if(prev !=curr &&curr !=next)returncurr;
30+
31+
// because there are no others criteria
32+
// remember to check the array's index to see if you miss anything
33+
// you can see that the even index should always be the start of the duplication
34+
// so if the sequence is broken: left of odd index is still a duplicate, the sequence
35+
// was broken before that index -> right = mid and vice versa
36+
if(mid %2 ==0) {
37+
if(curr !=prev)left =mid+1;
38+
elseright =mid;
39+
continue;
40+
}
41+
42+
if(curr ==prev)left =mid+1;
43+
elseright =mid;
44+
}
45+
returnnums[left];
46+
}
47+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp