136. Single Number

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.

Example 1:

Input: nums = [2,2,1]
Output: 1

Example 2:

Input: nums = [4,1,2,1,2]
Output: 4

Example 3:

Input: nums = [1]
Output: 1

Constraints:

1 <= nums.length <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104
Each element in the array appears twice except for one element which appears only once.

解法:

  1. 找出只出现1次的数,首先想到的是将数组排序,这样通过比较相邻数是否相等,即可找出来
  2. 建立一个Hashmap,当Hashmap中不存在某个数时,将其加入;当存在某个数时,将其删掉。最后的Hashmap中会仅剩下一个数,而这个数!就是答案。
    想法美滋滋,Hashmap yyds,
  public static int singleNumber(int[] nums) {
      Map<Integer, Integer> num = new HashMap<Integer, Integer>();
      for(int i=0;i<nums.length;i++){
          if(null == num.get(nums[i])){
              num.put(nums[i], 1);
          }else {
              num.remove(nums[i]);
          }
      }
      for(int result: num.keySet()){
          return result;
      }
      return 0;
  }

结果就一般,需要查一下时间复杂度和空间复杂度
3. 评论区看到:因为有“只有一个数字出现1次,其余均出现两次”————异或
妙,妙不可言。
大声喊出:交换律!结合率!自反性!

posted @ 2021-12-14 22:04  啤酒加点醋  阅读(26)  评论(0)    收藏  举报