【LeetCode】马三来刷题之 Single Number
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                【LeetCode】马三来刷题之 Single Number
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                最近每天刷題又找回了大一大二時天天晚上在機房刷ACM的那種感腳~,題目鏈接:https://leetcode.com/problems/single-number/? ?
136. Single Number
?- Total Accepted:?155864
- Total Submissions:?301077
- Difficulty:?Easy
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?
Subscribe?to see which companies asked this question
 
同樣是兩種方法過的,第一種方法是使用STL的map進行統計,如果一個數字出現出現一次,則將其對應的鍵的值進行++操作,最后遍歷整個map,
一旦發現值為1的就return 該鍵值對的鍵。第二種方法是先對數組排序,然后前一個和后一個依次相互比較,一旦發現有不同的,就返回前者,
如果遍歷到num.size()-2為止還沒有發現有不同的,那唯一的一個不同的值肯定就是最后一個了,所以直接return nums[nums.size()-1]。
第一種方法:
int singleNumber(vector<int>& nums) {if(nums.empty())return 0;map<int,int> m;for(int i=0;i<nums.size();i++){m[nums[i]]++;}for(map<int,int>::iterator it=m.begin();it!=m.end();it++){if((*it).second==1){return (*it).first;}}return 0; }
 
每天一道題,保持新鮮感,就這樣~
總結
以上是生活随笔為你收集整理的【LeetCode】马三来刷题之 Single Number的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 【News】华为海思AI视频监控芯片出货
- 下一篇: H3C HCL模拟器配置vlan划分案例
