【leetcode】Single Number (Medium) ☆
生活随笔
收集整理的這篇文章主要介紹了
【leetcode】Single Number (Medium) ☆
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
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)算法,還不能有輔助空間。開始用了各種O(n^2)的方法,都超時,后來突然頓悟了。異或可以消掉兩個相同數字。
直接把所有數字異或在一起,就是單獨的那個數字了。
#include <iostream> #include <vector> #include <algorithm> using namespace std;class Solution { public://異或可以把兩個相同的數字消除 O(n) ACint singleNumber3(int A[], int n) {int ans = 0;for(int i = 0; i < n; i++){ans ^= A[i];}return ans;} };int main() {Solution s;int a[9] = {0,0,1,1,2,3,2,3,4};int n = s.singleNumber3(a, 9);return 0; }?
轉載于:https://www.cnblogs.com/dplearning/p/4110566.html
總結
以上是生活随笔為你收集整理的【leetcode】Single Number (Medium) ☆的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2014年acm亚洲区域赛·鞍山站
- 下一篇: excel运行最多行数