本文共 1165 字,大约阅读时间需要 3 分钟。
LeetCode刷题:260. 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.
Example:
Input: [1,2,1,3,2,5]
Output: [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?算法设计
package com.bean.algorithm.basic;import java.util.HashSet;import java.util.Iterator;public class SingleNumberIII { public static int[] singleNumber(int[] nums) { int[] ans = { 0, 0 }; HashSeth = new HashSet (); for (int i = 0; i < nums.length; i++) { if (h.contains(nums[i])) { h.remove(nums[i]); } else { h.add(nums[i]); } } Iterator i = h.iterator(); if (i.hasNext()) ans[0] = i.next(); if (i.hasNext()) ans[1] = i.next(); return ans; } public static void main(String[] args) { // TODO Auto-generated method stub int[] arrays = new int[] { 1,2,1,3,2,5 }; int[] ANSWER = singleNumber(arrays); for(int i=0;i
程序运行结果:
3 5
转载地址:http://bitdi.baihongyu.com/