540. Single Element in a Sorted Array

540. Single Element in a Sorted Array

Given a sortedarray consisting of only integers where every element appears twice except forone element which appears once. Find this single element that appears onlyonce.

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

这个问题就是设置一个循环参数i,i的初始值为0,然后对比数组中的nums[i]和nums[i+1]是否一样,如果不一样,那么跳出for循环,返回nums[i]的值,如果一样,那么i=i+2,进一步验证nums[i+2]和nums[i+3]是否一样。

int singleNonDuplicate(int* nums, int numsSize) {
    int p=0;
    for(int i=0;i<numsSize;i=i+2){
        if(nums[i]!=nums[i+1]) {
            p=nums[i];
            break;
    }
    }
    return p;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章