欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode刷题:260. Single Number III

程序员文章站 2024-03-16 12:50:58
...

LeetCode刷题:260. Single 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.

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 };
		HashSet<Integer> h = new HashSet<Integer>();
		for (int i = 0; i < nums.length; i++) {
			if (h.contains(nums[i])) {
				h.remove(nums[i]);
			} else {
				h.add(nums[i]);
			}
		}
		Iterator<Integer> 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<ANSWER.length;i++) {
			System.out.print(ANSWER[i]+" ");
		}
		System.out.println();
	}

}

程序运行结果:

3 5