Codevs2605題解,leetcode題解

來源:互聯網
上載者:User

Codevs2605題解,leetcode題解

  • 寫在前面:學學stl,刷刷水題,練練vector

  • 題目描述 Description
    小明才會學數數,媽媽就開始難為他了。告訴他N(N<=1000000)個數字,問他哪一個數字出現的次數為奇數(保證N為奇數,資料中每個數字出現的次數只有一個為奇數次,每個數字為int範圍內)

  • 輸入描述 Input Description
    第一行一個N;第i+1行為第i個數字

  • 輸出描述 Output Description
    輸出僅僅一行,為出現奇數次的那個數字

  • 範例輸入 Sample Input
    5
    3
    6
    7
    6
    3

  • 範例輸出 Sample Output
    7

  • 資料範圍及提示 Data Size & Hint
    時間限制: 1 s
    空間限制: 32000 KB

  • 題解
    不知道為什麼分到了數論裡,一個雜湊表貌似就可以搞定了。每讀入一個數,從雜湊裡找:找到了就從雜湊裡刪掉,找不到就插入。最後掃一遍雜湊,哪個size不是0,就輸出哪個裡存的數。

  • Code

#include <cstdio>#include <vector>#include <algorithm>using namespace std;const int m = 299993;int n;vector <int> hash[300000];void ins(int p){    int k = p % m;    vector <int> :: iterator i;    bool b = false;    for(i = hash[k].begin(); i != hash[k].end(); i++) if((*i) == p)    {        b = true; break;    }    if(b) hash[k].erase(i);    else hash[k].push_back(p);}int main(){    int x;    scanf("%d", &n);    while(n--)    {        scanf("%d", &x);        ins(x);    }    for(int i = 0; i < m; ++i) if(hash[i].size() != 0)    {        printf("%d", hash[i][0]);        break;    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.