136. Single Number
2016-05-31 10:19
253 查看
题目:
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?
题意:
给定一个整数数组,除了其中一个元素只出现一次之外,其他每一个元素都出现两次。
note:
算法要求不使用额外的空间实现线性时间复杂度。
思路一:
直接轮训数组,将数组的每个元素做异或操作,结果即为single number。
代码:20ms
class Solution {
public:
int singleNumber(vector<int>& nums) {
int result = nums[0];
for(int i=1; i<nums.size(); i++){
result ^= nums[i];
}
return result;
}
};代码:20ms
class Solution {
public:
int singleNumber(vector<int>& nums) {
for(int i=1; i<nums.size(); i++){
nums[0] ^= nums[i];
}
return nums[0];
}
};
代码:20ms
class Solution {
public:
int singleNumber(vector<int>& nums) {
return nums.size() == 0 ? 0 : accumulate(nums.begin(), nums.end(), 0, bit_xor<int>());
}
};
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?
题意:
给定一个整数数组,除了其中一个元素只出现一次之外,其他每一个元素都出现两次。
note:
算法要求不使用额外的空间实现线性时间复杂度。
思路一:
直接轮训数组,将数组的每个元素做异或操作,结果即为single number。
代码:20ms
class Solution {
public:
int singleNumber(vector<int>& nums) {
int result = nums[0];
for(int i=1; i<nums.size(); i++){
result ^= nums[i];
}
return result;
}
};代码:20ms
class Solution {
public:
int singleNumber(vector<int>& nums) {
for(int i=1; i<nums.size(); i++){
nums[0] ^= nums[i];
}
return nums[0];
}
};
代码:20ms
class Solution {
public:
int singleNumber(vector<int>& nums) {
return nums.size() == 0 ? 0 : accumulate(nums.begin(), nums.end(), 0, bit_xor<int>());
}
};
相关文章推荐
- typeof关键字是C语言的应用
- Java读取Properties文件的七种方法
- java 初始化
- 2016第七届美国新泽西国际武术锦标赛五月底在大西洋城开赛
- 目诊知识2
- linux进程通信--消息队列
- WebClient 用法小结
- windows 用户登录和注销监控|windows session 状态改变监控
- tomcat端口配置文件解析
- 斯坦福机器学习公开课笔记
- IOS indexPathsForVisibleItems原理
- 用DeflateStream和GZipStream压缩数据
- spring-两个对象之间的属性拷贝工具
- UITextField点击选中文字
- 编程风格规范google版
- IOS-WebViewJavascriptBridge使用说明
- android 跳转到当前应用的详情页面
- javascript实现任务栏消息提示的简单实例
- 强悍的 Linux —— tar.xz 文件的解压
- Android中Gzip使用