当前位置:网站首页>】 【 LeetCode daily one problem - 540. The order of a single element of the array
】 【 LeetCode daily one problem - 540. The order of a single element of the array
2022-08-04 17:02:00 【IronmanJay】
一【题目类别】
- 二分查找
二【题目难度】
- 中等
三【题目编号】
- 540.有序数组中的单一元素
四【题目描述】
- 给你一个仅由整数组成的有序数组,其中每个元素都会出现两次,唯有一个数只会出现一次.
- 请你找出并返回只出现一次的那个数.
- 你设计的解决方案必须满足 O(log n) 时间复杂度和 O(1) 空间复杂度.
五【题目示例】
示例 1:
输入: nums = [1,1,2,3,3,4,4,8,8]
输出: 2示例 2:
输入: nums = [3,3,7,7,10,11,11]
输出: 10
六【题目提示】
- 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
七【解题思路】
- 主要还是二分查找的思路
- Only the judgment conditions have changed,注意读题目:If a section does not have a single element before it,Then the length of this part must be even,index is odd,Otherwise, the length is an odd number,The index is also an even number
- So we still get the index of the middle element,如果索引为奇数,Then it means that the previous ones appear in pairs,There is no single element,But it is also necessary to judge whether the latter and the former are equal,That is to judge whether it is a pile,如果是的话,Explain that there is no single element on the left,Then modify the left index subscript to the right
- If the index is even,Explain that there must be a single element in the left part,Modify the right index subscript to the left
- 最后还需要注意whileThe judgment condition is that the left index is less than the right index,不能是小于等于,否则会死循环
八【时间频度】
- 时间复杂度: O ( l o g 2 N ) O(log_{2}N) O(log2N),其中 N N N为数组元素个数
- 空间复杂度: O ( 1 ) O(1) O(1)
九【代码实现】
- Java语言版
package BinarySearch;
public class p540_SingleElementInSortedArray {
public static void main(String[] args) {
int[] nums = {
1, 1, 2, 3, 3, 4, 4, 8, 8};
int res = singleNonDuplicate(nums);
System.out.println("res = " + res);
}
public static int singleNonDuplicate(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (mid % 2 == 1) {
mid--;
}
if (nums[mid] == nums[mid + 1]) {
left = mid + 2;
} else {
right = mid;
}
}
return nums[left];
}
}
- C语言版
#include<stdio.h>
int singleNonDuplicate(int* nums, int numsSize)
{
int left = 0;
int right = numsSize - 1;
while (left < right)
{
int mid = left + (right - left) / 2;
if (mid % 2 == 1)
{
mid--;
}
if (nums[mid] == nums[mid + 1])
{
left = mid + 2;
}
else
{
right = mid;
}
}
return nums[left];
}
/*主函数省略*/
十【提交结果】
Java语言版

C语言版

边栏推荐
猜你喜欢
随机推荐
【LeetCode每日一题】——540.有序数组中的单一元素
88.(cesium之家)cesium聚合图
智慧场馆的功能有哪些
泰坦尼克号沉船数据之美——起于悲剧,止于浪漫
黑龙江移动新魔百盒M411A_2+8_S905L3A_线刷固件包
15天升级打怪,成为虚拟时尚创作者
代码重构:面向单元测试
机器学习(十四):K均值聚类(kmeans)
taro 滚动组件ScrollView
码蹄集 - MT2094 - 回文之时:第4组数据错误
WEB 渗透之越权
R语言使用cov函数计算矩阵或者dataframe数据变量之间的协方差、cor函数计算相关性、cor函数通过method参数指定相关性、相关性计算方法Pearson,Spearman, Kendall
icu是哪个国家的域名?icu是什么域名?
湖北电信天邑TY1608_S905L3B_MT7668_卡刷固件包
【LeetCode每日一题】——374.猜数字大小
机器学习(十六):主成成分分析(PCA)
机器人示教编程与离线编程的优缺点对比
机器学习(十九):梯度提升回归(GBR)
【Gazebo入门教程】第二讲 模型库导入与可视化机器人建模(模型编辑器)
美容院管理系统有哪些促销方式?









