LeetCode //C - 540. Single Element in a Sorted Array

540. Single Element in a Sorted Array

You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.

Return the single element that appears only once.

Your solution must run in O(log n) time and O(1) space.

Example 1:

Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2

Example 2:

Input: nums = [3,3,7,7,10,11,11]
Output: 10

Constraints:
  • 1 < = n u m s . l e n g t h < = 1 0 5 1 <= nums.length <= 10^5 1<=nums.length<=105
  • 0 < = n u m s [ i ] < = 1 0 5 0 <= nums[i] <= 10^5 0<=nums[i]<=105

From: LeetCode

Link: 540. Single Element in a Sorted Array


Solution:

Ideas:

1. Pairs Observation: In a perfectly paired array where each element appears exactly twice, if you pick any even index (0, 2, 4,...), the next index should have the same value if there's no single element disrupting the pairing.

2. Detecting the Single Element Influence: When the single element is introduced, it disrupts these pairings. Specifically, the first occurrence of every element in a disrupted array will start appearing at an even index and end at an odd index (before the single element appears).

3. Binary Search Strategy:

  • Check the middle index of the array.
  • If the middle index is even, then check the next element. If they are the same, it means the single element is ahead; otherwise, it's behind.
  • If the middle index is odd, then check the previous element. If they are the same, it means the single element is ahead; otherwise, it's behind.
  • Adjust the search boundaries accordingly until you find the single element.
Code:
c 复制代码
int singleNonDuplicate(int* nums, int numsSize) {
    int low = 0, high = numsSize - 1;
    while (low < high) {
        int mid = low + (high - low) / 2;
        // Ensure mid is even. If mid is odd, decrease by 1 to make it even.
        if (mid % 2 == 1) mid--;

        // Check pairs: nums[mid] should be the same as nums[mid + 1]
        if (nums[mid] == nums[mid + 1]) {
            // If they are the same, move to the right half
            low = mid + 2;
        } else {
            // If not the same, move to the left half
            high = mid;
        }
    }
    // Low should point to the single element
    return nums[low];
}
相关推荐
yuanbenshidiaos几秒前
C++----------函数的调用机制
java·c++·算法
唐叔在学习5 分钟前
【唐叔学算法】第21天:超越比较-计数排序、桶排序与基数排序的Java实践及性能剖析
数据结构·算法·排序算法
ALISHENGYA24 分钟前
全国青少年信息学奥林匹克竞赛(信奥赛)备考实战之分支结构(switch语句)
数据结构·算法
chengooooooo26 分钟前
代码随想录训练营第二十七天| 贪心理论基础 455.分发饼干 376. 摆动序列 53. 最大子序和
算法·leetcode·职场和发展
jackiendsc33 分钟前
Java的垃圾回收机制介绍、工作原理、算法及分析调优
java·开发语言·算法
姚先生9743 分钟前
LeetCode 54. 螺旋矩阵 (C++实现)
c++·leetcode·矩阵
FeboReigns1 小时前
C++简明教程(文章要求学过一点C语言)(1)
c语言·开发语言·c++
FeboReigns1 小时前
C++简明教程(文章要求学过一点C语言)(2)
c语言·开发语言·c++
游是水里的游2 小时前
【算法day20】回溯:子集与全排列问题
算法
_小柏_2 小时前
C/C++基础知识复习(43)
c语言·开发语言·c++