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 }
标签:
LeetCode
, Binary Search
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何在 .NET 中 使用 ANTLR4
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 想让你多爱自己一些的开源计时器
· Cursor预测程序员行业倒计时:CTO应做好50%裁员计划
· 大模型 Token 究竟是啥:图解大模型Token
· 如何在 .NET 中 使用 ANTLR4
· 用99元买的服务器搭一套CI/CD系统