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];
}
相关推荐
csdn_aspnet4 小时前
C语言 Lomuto分区算法(Lomuto Partition Algorithm)
c语言·开发语言·算法
谙弆悕博士4 小时前
【附C源码】从零实现C语言堆数据结构:原理、实现与应用
c语言·数据结构·算法··数据结构与算法
gaosushexiangji7 小时前
DIC系统推荐:基于千眼狼三维数字图像相关的无人机旋翼疲劳试验全场应变与位移测量
人工智能·算法
小王C语言9 小时前
【线程概念与控制】:线程封装
jvm·c++·算法
圣保罗的大教堂9 小时前
leetcode 796. 旋转字符串 简单
leetcode
kyle~9 小时前
工程数学---点云配准卡布施(Kabsch)算法(求解最优旋转矩阵)
线性代数·算法·矩阵
三品吉他手会点灯9 小时前
C语言学习笔记 - 35.数据类型 - printf函数的非输出控制符与格式优化
c语言·开发语言·笔记·学习
张二娃同学9 小时前
03_变量常量与输入输出_printf与scanf详解
算法
江南十四行10 小时前
并发编程(一)
java·jvm·算法
Ghost Face...10 小时前
U-Boot SPL阶段与主阶段深度解析:从ROM到Kernel的完整引导之旅(ARMv8)
c语言