File tree 2 files changed +34
-0
lines changed
2 files changed +34
-0
lines changed Original file line number Diff line number Diff line change 430
430
537|[ Complex Number Multiplication] ( ./0537-complex-number-multiplication.js ) |Medium|
431
431
538|[ Convert BST to Greater Tree] ( ./0538-convert-bst-to-greater-tree.js ) |Medium|
432
432
539|[ Minimum Time Difference] ( ./0539-minimum-time-difference.js ) |Medium|
433
+ 540|[ Single Element in a Sorted Array] ( ./0540-single-element-in-a-sorted-array.js ) |Medium|
433
434
541|[ Reverse String II] ( ./0541-reverse-string-ii.js ) |Easy|
434
435
542|[ 01 Matrix] ( ./0542-01-matrix.js ) |Medium|
435
436
543|[ Diameter of Binary Tree] ( ./0543-diameter-of-binary-tree.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 540. Single Element in a Sorted Array
3
+ * https://leetcode.com/problems/single-element-in-a-sorted-array/
4
+ * Difficulty: Medium
5
+ *
6
+ * You are given a sorted array consisting of only integers where every element appears
7
+ * exactly twice, except for one element which appears exactly once.
8
+ *
9
+ * Return the single element that appears only once.
10
+ *
11
+ * Your solution must run in O(log n) time and O(1) space.
12
+ */
13
+
14
+ /**
15
+ * @param {number[] } nums
16
+ * @return {number }
17
+ */
18
+ var singleNonDuplicate = function ( nums ) {
19
+ let left = 0 ;
20
+ let right = nums . length - 1 ;
21
+
22
+ while ( left < right ) {
23
+ let middle = left + Math . floor ( ( right - left ) / 2 ) ;
24
+ middle = middle - ( middle % 2 ) ;
25
+ if ( nums [ middle ] === nums [ middle + 1 ] ) {
26
+ left = middle + 2 ;
27
+ } else {
28
+ right = middle ;
29
+ }
30
+ }
31
+
32
+ return nums [ left ] ;
33
+ } ;
You can’t perform that action at this time.
0 commit comments