136.Single Number
时间:2015-01-30 09:10:45
收藏:0
阅读:247
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 itwithout using extra memory?
第二种不使用额外空间的方法,比第一种慢一点点~
//main.cpp #pragma once #include<iostream> using namespace std; int singleNumber2(int A[], int n) { int result = *A; for (int i = 1; i < n; i++) result = result^A[i]; return result; } int singleNumber1(int A[], int n) { for (int i = 1; i < n; i++) *A = *A^A[i]; return *A; } void main() { int a[] = { 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1 }; int n = sizeof(a) / sizeof(int); cout << singleNumber(a, 11) << endl; system("pause"); }
评论(0)