本文主要是介绍[leetcode]--260. Single Number III,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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,
这篇关于[leetcode]--260. Single Number III的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!