LeetCode-Single Element in a Sorted Array

Description:
Given a sorted array consisting of only integers where every element appears twice except for one element which appears 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.

题意:给定一个已排序的数组,要求找出在数组中仅出现一次的那个元素(其他所有元素均出现两次);

解法:考虑异或操作,对于元素a来说

  • a ^ a = 0
  • a ^ 0 = a

因此,我们对数组中的所有元素进行异或操作,相同的元素异或得到结果0,而0与数组中仅出现一次的元素再异或得到的就是元素本身;其时间复杂度为O(n);

Java
class Solution {
    public int singleNonDuplicate(int[] nums) {
        int result = 0;
        for (int num : nums) {
            result ^= num;
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值