Skip to content

Commit 26ca5e5

Browse files
authored
Merge pull request #215 from Codeioholic/my_contribution
Added single_Element_In_Sorted_Array.java in Coding folder
2 parents 9227aa9 + 2e0413c commit 26ca5e5

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*
2+
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
3+
4+
Return the single element that appears only once.
5+
6+
Your solution must run in O(log n) time and O(1) space.
7+
8+
9+
10+
Example 1:
11+
12+
Input: nums = [1,1,2,3,3,4,4,8,8]
13+
Output: 2
14+
Example 2:
15+
16+
Input: nums = [3,3,7,7,10,11,11]
17+
Output: 10
18+
*/
19+
20+
public class Solution {
21+
public int singleNonDuplicate(int [] nums) {
22+
int left = 0;
23+
int right = nums.length-1;
24+
25+
while(left < right) {
26+
int mid = left + (right-left)/2;
27+
28+
if(nums[mid] == nums[mid-1]) {
29+
int isEven = right-mid;
30+
if(isEven % 2 == 0) {
31+
right = mid+2;
32+
}
33+
else {
34+
left = mid+1;
35+
}
36+
}
37+
else if (numsp[mid] == nums[mid+1]) {
38+
int isEven = right-mid;
39+
if(isEven % 2 == 0) {
40+
left = mid+2;
41+
}
42+
else {
43+
right = mid-1
44+
}
45+
}
46+
else {
47+
return nums[mid];
48+
}
49+
}
50+
return nums[left];
51+
}
52+
53+
public static void main(String[]args) {
54+
int [] arr = {1,1,2,3,3,4,4,8,8};
55+
int duplicate_number = singleNonDuplicate(arr);
56+
System.out.println(duplicate_number);
57+
}
58+
}

0 commit comments

Comments
 (0)