LeetCode | 540. Single Element in a Sorted Array

540. Single Element in a Sorted Array

  • Total Accepted: 1638
  • Total Submissions: 2985
  • Difficulty: Medium
  • Contributors: rajaditya

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.

思路:二分查找,由于总元素个数为奇数个,可以将数组分为左右两部分,然后答案在奇数子数组中
#include <iostream>
#include <vector>
using namespace std;

int singleNonDuplicate(vector<int>& nums)
{
    if(nums.size() == 1)
        return nums[0];
    if(nums[0] != nums[1])
        return nums[0];
    if(nums[nums.size()-1] != nums[nums.size()-2])
        return nums[nums.size()-1];

    //Binary Search
    int l = 0, r = nums.size()-1;

    while(l <= r)//"=" is must......
    {
        int mid = (l+r)/2;
        if(nums[mid]!=nums[mid-1] && nums[mid]!=nums[mid+1])
            return nums[mid];
        if(nums[mid] == nums[mid+1])//change the array to two parts:[l,mid-1]&&[mid+2,r];
        {
            if((mid-l) % 2 == 1)
                r = mid-1;
            else
                l = mid+2;
        }
        else if(nums[mid] == nums[mid-1])
        {
            if((mid-l-1) % 2 == 1)
                r = mid-2;
            else
                l = mid+1;
        }
    }
    /*
    if(nums[0] != nums[1])
    {
        return nums[0];
    }
    else if(nums[nums.size()-1] != nums[nums.size()-2])
    {
        return nums[nums.size()-1];
    }
    else
    {
        for(int i=1;i<nums.size();i++)
        {
            if(nums[i]!=nums[i-1] && nums[i]!=nums[i+1])
            {
                return nums[i];
            }
        }
    }*/
    return -1;
}

int main()
{
    int t;
    vector<int> v;
    while(cin>>t)
        v.push_back(t);
    cout<<singleNonDuplicate(v)<<endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值