[leetcode]--260. Single Number III

来源:互联网 发布:网络培训个人研修计划 编辑:程序博客网 时间:2024/06/06 09:36

Question 260:

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 static int[] singleNumber(int[] nums) {    //遍历数组,看每个数据是否存在其余可以亦或为0的数据    for(int i=0; i<nums.length-1; i++){        if(nums[i]==0)            continue;        for (int j=i+1; j<nums.length; j++){            if( (nums[i]^nums[j]) == 0 ) {                nums[i]=0;                nums[j]=0;                break;            }        }    }    //找出非0的两个数据    int[] result = new int[2];    int j=0;    for(int i=0; i<nums.length; i++){        if(nums[i] != 0){            result[j++]=nums[i];        }    }    return result;}

测试例子:

public static void main(String[] args) {    int [] nums = {1, 2, 1, 3, 2, 5};    int [] result = singleNumber(nums);    for(int i: result){        LogUtil.log_debug(""+i);    }}

运行结果:

3,5,
0 0