LeetCode 540. Single Element in a Sorted Array

原题链接在这里:https://leetcode.com/problems/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. Find this single element that appears only once.

Example 1:

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

Example 2:

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

Note: Your solution should run in O(log n) time and O(1) space.

题解:

When doing binary search, if mid is odd, mid minus 1, as we want to get the first value of pair.

Compares nums[mid] with nums[mid+1].

If they are not equal, single must be on its left, r = mid.

If they are equal, this is a pair, single must be on its right, l = mid + 2.

Eventually return nums[l].

Time Complexity: O(logn). n = nums.length.

Space: O(1).

AC Java:

复制代码
 1 class Solution {
 2     public int singleNonDuplicate(int[] nums) {
 3         int l = 0;
 4         int r = nums.length - 1;
 5         while(l < r){
 6             int mid = l + (r - l) / 2;
 7             if(mid % 2 == 1){
 8                 mid--;
 9             }
10             
11             if(nums[mid] != nums[mid + 1]){
12                 r = mid;
13             }else{
14                 l = mid + 2;
15             }
16         }
17         
18         return nums[l];
19     }
20 }
复制代码

类似Find Minimum in Rotated Sorted Array.

posted @   Dylan_Java_NYC  阅读(293)  评论(0编辑  收藏  举报
编辑推荐:
· 如何在 .NET 中 使用 ANTLR4
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
阅读排行:
· 想让你多爱自己一些的开源计时器
· Cursor预测程序员行业倒计时:CTO应做好50%裁员计划
· 大模型 Token 究竟是啥:图解大模型Token
· 如何在 .NET 中 使用 ANTLR4
· 用99元买的服务器搭一套CI/CD系统
点击右上角即可分享
微信分享提示