I am doing leetcode 540. Single Element in a Sorted Array using c++. The problem is: You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once.
Here is a example:
Input: [1,1,2,3,3,4,4,8,8]
Output: 2
I run into runtime error again:
Runtime Error Message:
AddressSanitizer: heap-buffer-overflow on address 0x602000000034 at pc 0x0000004056da bp 0x7ffcd2cff910 sp 0x7ffcd2cff908
Here is my code and it's super easy to understand.
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int n = nums.size();
int i = 1;
int output;
if(nums[0] != nums[1])
return nums[0];
if(nums[n-1] != nums[n-2])
return nums[n-1];
for(i = 1; i < n-1; i++)
{
if(nums[i]!=nums[i-1] && nums[i]!=nums[i+1])
{
output = nums[i];
break;
}
}
return output;
}
};
I really hope someone can help me. I met this problem several times and I have no clue what's going on.