Advertisement
1988coder

540. Single Element in a Sorted Array

Jan 28th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/single-element-in-a-sorted-array/
  2.  
  3. /**
  4.  * Binary Search
  5.  *
  6.  * Consider a1, a1, a2, a2, a3, a4, a4, a5, a5. Since the input array is sorted,
  7.  * single element will always be on the even index. On the left of single
  8.  * element, the pairs will be (even, odd). On the right of single element, the
  9.  * pairs will be (odd, even).
  10.  *
  11.  * Time Complexity: O(log N)
  12.  *
  13.  * Space Complexity: O(1)
  14.  */
  15. class Solution {
  16.     public int singleNonDuplicate(int[] nums) throws IllegalArgumentException {
  17.         if (nums == null || nums.length == 0) {
  18.             throw new IllegalArgumentException("Invalid Input");
  19.         }
  20.  
  21.         int left = 0;
  22.         int right = nums.length - 1;
  23.  
  24.         while (left < right) {
  25.             // The first element of the middle pair should be at an even index if the left
  26.             // part is sorted.
  27.             int mid = left + (right - left) / 2;
  28.             if (mid % 2 != 0) {
  29.                 mid--;
  30.             }
  31.  
  32.             // Found a pair. The single element must be on the right.
  33.             if (nums[mid] == nums[mid + 1]) {
  34.                 left = mid + 2;
  35.             } else {
  36.                 // Did not find a pair. The single element must be on the left.
  37.                 right = mid;
  38.             }
  39.         }
  40.  
  41.         // 'left' should always be at the beginning of a pair.
  42.         // When 'left > right', left must be the single element.
  43.         return nums[left];
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement