【LeetCode OJ 260】Single Number III

来源:互联网 发布:福昕pdf阅读器for mac 编辑:程序博客网 时间:2024/06/07 19:59

题目链接: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; }}


0 0