首页 > 代码库 > Single Number i and ii
Single Number i and ii
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。