LeetCode—Single Number

来源:互联网 发布:淘宝购物车东西不见了 编辑:程序博客网 时间:2024/05/29 15:07

题目:

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

题解:写了一个时间复杂度为O(n^2)的代码如下,百度了一下才知道利用一个数与本身异或结果为0,而一个数与0异或仍为本身这两条规则。

#include "stdafx.h"#include <iostream>using namespace  std;int singleNumber(int A[], int n){int flag = 0;for (int i = 0; i<n; ++i){for (int j = 0; j<n; j++){if (i==j){continue;}else if (A[i] == A[j]){flag = 0;break;}else{flag = 1;continue;}}if (flag){return A[i];break;}}}int _tmain(int argc, _TCHAR* argv[]){int A[] = { 1, 2, 3, 4,9 , 2, 1, 4, 5, 6, 5 ,6,8,8,9};cout << singleNumber(A, sizeof(A)/sizeof(int)) << endl;return 0;}



0 0
原创粉丝点击