码迷,mamicode.com
首页 > 其他好文 > 详细

Single Number i and ii

时间:2014-10-19 23:00:35      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:blog   io   ar   java   for   strong   sp   div   on   

Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

c++版:

class Solution {
public:
   int singleNumber(int arr[] , int length)
{
    int result=arr[0];
    for(int i = 1 ; i < length ; ++i)
        result = result ^ arr[i];
     return result;
 }
};

 Java版:

public class Solution {
    public int singleNumber(int[] A) {
    int result=A[0];
    for(int i=1;i<A.length;i++){
        result=result^A[i];
    }
    return result;
    }
}

  

Single Number II

Given an array of integers, every element appears three times except for one. Find that single one.

C++版:

class Solution {
public:
  int singleNumber(int A[], int n) {  
    if(n < 0 || n%3 != 1)    return -1;
    map<int, int> mp;
    map<int, int>::iterator it;
    for(int i = 0; i<n; i++) {
        it = mp.find(A[i]);
        if(it == mp.end())
            mp[A[i]] = 1;
        else
           mp[A[i]] += 1;
    }
    for(it = mp.begin(); it != mp.end(); it++) {
        if((*it).second != 3)   return (*it).first;
    }
    }
};

  

Single Number i and ii

标签:blog   io   ar   java   for   strong   sp   div   on   

原文地址:http://www.cnblogs.com/zlz-ling/p/4035613.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!