The Solution to Leetcode 136 Single Number

来源:互联网 发布:网络运营需要什么技术 编辑:程序博客网 时间:2024/06/05 18:29

Question:

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?

思路:将所给数组按升序排序,两个两个的扫描,当相邻两个数字不一样时,那个就是single one。

Answer:

class Solution {public:    int singleNumber(vector<int>& nums) {        int i=0;        if(nums.size()==1)           return nums[i];                sort(nums.begin(), nums.end());        for(i==0;i<nums.size();i=i+2)        {            if(nums[i]!=nums[i+1])             return nums[i];        }    }};

run code results:
Your input
[9 5 9 3 4 5 4 2 1 2 0 1 0]
Your answer
3
Expected answer
3


0 0
原创粉丝点击