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];
}
相关推荐
进击的小头2 分钟前
第8篇:线性二次型调节器
python·算法·动态规划
Z9fish3 分钟前
sse哈工大C语言编程练习42
c语言·开发语言·算法
炸膛坦客9 分钟前
单片机/C语言八股:(十三)C 语言实现矩阵乘法
c语言·开发语言·矩阵
一个有毅力的吃货17 分钟前
这个SKILL打通了AI写公众号文章的最后一公里
css·算法
free-elcmacom21 分钟前
C++ 函数占位参数与重载详解:从基础到避坑
java·前端·算法
Frostnova丶24 分钟前
LeetCode 1415. 长度为 n 的开心字符串中字典序第 k 小的字符串
数据结构·算法·leetcode
美好的事情能不能发生在我身上24 分钟前
Leetcode热题100中的:技巧专题
算法·leetcode·职场和发展
荣光属于凯撒27 分钟前
P15755 [JAG 2025 Summer Camp #1] JAG Box
c++·算法·贪心算法
AI科技星40 分钟前
基于v≡c空间光速螺旋量子几何归一化统一场论第一性原理的时间势差本源理论
人工智能·线性代数·算法·机器学习·平面
云泽80844 分钟前
蓝桥杯算法精讲:哈夫曼编码的贪心思想与落地实现
算法·职场和发展·蓝桥杯