【LeetCode OJ 260】Single Number III
2016-01-25 16:30
417 查看
题目链接:https://leetcode.com/problems/single-number-iii/
题目:Given an array of numbers
in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given
Note:
The order of the result is not important. So in the above example,
also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
解题思路:题意为给定一个数组,只有两个数字出现了一次,其它均出现了两次,请找出这两个出现了一次的数。题目要求算法的时间复杂度为线性的,空间复杂度为常量,本题给出了一个粗暴的解法:
代码示例:
题目:Given an array of numbers
nums,
in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given
nums = [1, 2, 1, 3, 2, 5], return
[3, 5].
Note:
The order of the result is not important. So in the above example,
[5, 3]is
also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
解题思路:题意为给定一个数组,只有两个数字出现了一次,其它均出现了两次,请找出这两个出现了一次的数。题目要求算法的时间复杂度为线性的,空间复杂度为常量,本题给出了一个粗暴的解法:
代码示例:
public class Solution { public int[] singleNumber(int[] nums) { int[] result=new int[2]; List<Integer> temp=new ArrayList<Integer>(); for(int i=0;i<nums.length;i++) { //如果不存在,则加入temp中 if(!temp.contains(nums[i])) { temp.add(nums[i]); } //不存在,表示存在两次,就从temp除去该数 else { temp.remove((Object)nums[i]); } } result[0]=temp.get(0); result[1]=temp.get(1); return result; } }
相关文章推荐
- .map文件的作用以及在chorme下会报错找不到jquery-1.10.2.min.map文件,404 的原因
- .NET 拼音汉字转化(全面)
- ORA-12519: TNS:no appropriate service handler found 解决(转)
- 【转】OpenGL开发环境配置
- 【转】MySQL忘记root密码
- 【转】每个程序员都必须遵守的编程原则
- 【转】Log4j 配置最全说明
- 【转】C++ ZLib压缩与解压缩
- 【转】程序debug正常release错误
- 【转】C++ Vector 使用心得
- 【转】select,iocp,epoll,kqueue及各种I/O复用机制
- 【转】关于Socket和IOCP的一些值得注意的地方
- 【转】通过程序来配置log4j,替代log4j.properties
- MySQL老旧版本下载地址
- IT人员迅速提升自我效率的十大方法
- 如何检测网络端口是否被占用
- 编写安全代码:数组和指针的本质以及何时不能互换
- 实践C++ 代码维护的思考
- 我的C++技巧总结
- 【转】内存溢出处理方法