LeetCode OJ 260Single Number III

Posted xujian_2014

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode OJ 260Single Number III相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode.com/problems/single-number-iii/

题目: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:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. 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;
	 


以上是关于LeetCode OJ 260Single Number III的主要内容,如果未能解决你的问题,请参考以下文章

leetcode260 Single Number III

[leetcode-260-Single Number III]

leetcode260. Single Number III

[LeetCode] 260. Single Number III(位运算)

LeetCode-- 260. Single Number III

[LeetCode] 260. Single Number III 单独数 III