首页 > 其他 > 详细

leetcode 136. Single Number

时间:2016-03-23 19:51:30      阅读:139      评论:0      收藏:0      [点我收藏+]

136. Single Number


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?

 1 class Solution {
 2 public:
 3     int singleNumber(vector<int>& nums) {
 4         sort(nums.begin(),nums.end());
 5         if(nums.size()==1)
 6         {
 7             return nums[0];
 8         }
 9         else if (nums[0]!=nums[1])
10         {
11             return nums[0];
12         }
13         else
14         {
15             
16             for(int i = 1;i < nums.size()-1;i++)
17             {
18                 if((nums[i]!=nums[i-1])&&(nums[i]!=nums[i+1])) 
19                 {
20                     return nums[i];
21                 }
22             }
23         return nums[nums.size()-1];
24         }
25     }
26 };

注意:1.寻找序列内单个的数。

2.我的方法(线性时间复杂度,不利用其他空间):

先sort一遍排列,和前后两个数都不相等的就是所求,序列长度为1为边界条件

3.快速方法:!!!所有数按位异或即为结果(因为异或满足结合律!!!)

leetcode 136. Single Number

原文:http://www.cnblogs.com/dystopia/p/5312490.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!