给定一个整数数组,除了某个元素外其余元素均出现两次。请找出这个只出现一次的元素。
备注:
你的算法应该是一个线性时间复杂度。 你可以不用额外空间来实现它吗?
import java.util.HashMap; public class Main { public static void main(String[] args) { int[] nums = {1, 1, 2, 3, 3, 2, 4, 5, 4, 4, 4}; Solution solution = new Solution(); Integer singleNum = solution.singleNumber(nums); System.out.println("singleNum :" + singleNum); } static class Solution { public int singleNumber(int[] nums) { if (nums == null) { System.out.println("Array Is Empty"); return -1; } HashMap<Integer, Integer> hashMap = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (null != hashMap.put(nums[i], i)) { hashMap.remove(nums[i]); } } if (hashMap.keySet().iterator().hasNext()) { return hashMap.keySet().iterator().next(); } System.out.println("Array Is Symmetry"); return -1; } } //v1 /* array public int singleNumber(int[] nums) { int singleNum; List list = Arrays.asList(nums); list.sort(new Comparator() { @Override public int compare(Object o1, Object o2) { return Integer.parseInt(o1.toString()) > Integer.parseInt(o2.toString()) ? 1 : 0; } }); Integer j = 0; for (int i = 0; i < list.size(); i = i+2) { j = i + 1; if (j == list.size()) { return Integer.parseInt(list.get(i).toString()); } if (list.get(i) != list.get(j)){ return Integer.parseInt(list.get(i).toString()); } } return (int)list.get(0); } }*/ }