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];
}
相关推荐
涛ing1 小时前
32. C 语言 安全函数( _s 尾缀)
linux·c语言·c++·vscode·算法·安全·vim
独正己身2 小时前
代码随想录day4
数据结构·c++·算法
厂太_STAB_丝针3 小时前
【自学嵌入式(8)天气时钟:天气模块开发、主函数编写】
c语言·单片机·嵌入式硬件
利刃大大5 小时前
【回溯+剪枝】找出所有子集的异或总和再求和 && 全排列Ⅱ
c++·算法·深度优先·剪枝
charlie1145141915 小时前
从0开始使用面对对象C语言搭建一个基于OLED的图形显示框架(协议层封装)
c语言·驱动开发·单片机·学习·教程·oled
*TQK*5 小时前
ZZNUOJ(C/C++)基础练习1041——1050(详解版)
c语言·c++·编程知识点
Rachela_z5 小时前
代码随想录算法训练营第十四天| 二叉树2
数据结构·算法
细嗅蔷薇@6 小时前
迪杰斯特拉(Dijkstra)算法
数据结构·算法
追求源于热爱!6 小时前
记5(一元逻辑回归+线性分类器+多元逻辑回归
算法·机器学习·逻辑回归
ElseWhereR6 小时前
C++ 写一个简单的加减法计算器
开发语言·c++·算法