1 Star 0 Fork 0

Byte/algorithm

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
文件
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
array_11.java 1.08 KB
Copy Edit Raw Blame History
Gavery authored 2022-04-10 22:51 +08:00 . review
package arrays;
/**题目:有序数组中的单身数字
*
* @Author Gavin
* @date 2022.01.03 10:54
*/
public class array_11 {
/**
* 第一种方法 :循环所有的元素进行异或操作,略
* Time:O(n)
*/
/**
* 第二种方法:利用有序这个特点使用二分搜索法
*/
//Time:O(log(n)) Space:O(1)
public static int solution(int[] nums){
int low=0,high=nums.length-1;
while (low<=high){
int mid=low+(high-low)/2;
if(mid-1>=0&&nums[mid-1]==nums[mid]){
--mid;
}else if(mid+1<=high&&nums[mid+1]==nums[mid]){}
else{
return nums[mid];
}
/**
* 这里就是核心点:
* 因为单身数字都不是成对出现的,所以有一边是为奇数
*/
if((mid-low)%2==1)high=mid-1;
else low=mid+2;
}
return -1;
}
public static void main(String[] args) {
int[] array=new int[]{2,2,3,3,4};
System.out.println(solution(array));
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/Gavery/algorithm.git
git@gitee.com:Gavery/algorithm.git
Gavery
algorithm
algorithm
master

Search