int singleNumber(int* nums, int numsSize){
int i = 1;
int data;
data = nums[0];
while (i < numsSize) {
if (data != nums[i]) {
i++;
}
else {
i += 2;
data = nums[i+1];
}
}
return data;
}
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1]
输出: 1
示例 2:
输入: [4,1,2,1,2]
输出: 4
代码报了一长串的错误,奇怪的是,在用VSCode环境debug时,并未报错。搜索问题发现,LeetCode 使用了AddressSanitizer检查是否存在内存非法访问,该问题检查内存非法访问问题,发现问题出在这里
else {
i += 2;
data = nums[i+1];
}
在data赋值前先进行i+2操作,再执行num[i+1]时既有可能引起i大于size值,使得数组nums[]访问越界,修改后执行ok
else {
data = nums[i+1];
i += 2;
}
==30==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x603000000028 at pc 0x0000004018d1 bp 0x7ffc7efb9960 sp 0x7ffc7efb9958
READ of size 4 at 0x603000000028 thread T0
#2 0x7f54691a52e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202e0)
0x603000000028 is located 4 bytes to the right of 20-byte region [0x603000000010,0x603000000024)
allocated by thread T0 here:
#0 0x7f546a62f2b0 in malloc (/usr/local/lib64/libasan.so.5+0xe82b0)
#3 0x7f54691a52e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202e0)
Shadow bytes around the buggy address:
0x0c067fff7fb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7fc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7fd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7fe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x0c067fff8000: fa fa 00 00 04[fa]fa fa fa fa fa fa fa fa fa fa
0x0c067fff8010: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8020: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8030: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8040: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8050: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Container overflow: fc
Array cookie: ac
Intra object redzone: bb
ASan internal: fe
Left alloca redzone: ca
Right alloca redzone: cb
==30==ABORTIN