落单的数

来源:互联网 发布:网络言论自由 高中作文 编辑:程序博客网 时间:2024/06/09 19:52

给出2*n + 1 个的数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字

思路:先排序,然后从第0个开始相邻的两个比较,相等就跳过这两个进行比较,出现不等的,返回

注意长度为len的vector转成数组后,因为i一定为偶数,len一定为单数,i=len-1时,访问a[i+1]时越界,所以补上a[len]=0;


class Solution{public:/** @param A: An integer array* @return: An integer*/int singleNumber(vector<int> A){// write your code hereint len = A.size();int *a = new int[len+1];//a = A;if (!A.empty()){for (int i = 0; i < len; i++){a[i] = A[i];}}sort(a, a + len);a[len] = 0;for (int i = 0; i < len;i++,i++){if (a[i] != a[i + 1]){return a[i];}}//return 0;}};int main(int argc, char *argv[]){vector<int> a;int a1[] = { 1, 2, 2, 1, 3, 4, 3 };//1,1,2,2,3,3,4for (int i = 0; i < 7; i++){a.push_back(a1[i]);}Solution A;cout << A.singleNumber(a) << endl;system("pause");return 0;}