LeetCode 136.只出现一次的数字

题目:

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

说明:

你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:

输入: [2,2,1]
输出: 1
示例 2:

输入: [4,1,2,1,2]
输出: 4

  解题思路:

  1.HashMap(第一反应),不完全符合题目要求,使用了额外的空间

class Solution {
  public int singleNumber(int[] nums) {
      Map<Integer, Integer> map=new HashMap<>();
      for(int num:nums) {
        if (map.containsKey(num)) {
          map.put(num, map.get(num)+1);
        }else {
          map.put(num, 1);
        }
      }
      for(Map.Entry<Integer, Integer> entry:map.entrySet()) {
        if (entry.getValue()==1) {
          return entry.getKey();
        }
      }
      throw new IllegalArgumentException();
  }
}

  时间复杂度O(n),空间复杂度O(n)

  2.HashSet,也使用了额外的空间,比第一种写法稍微好一点

class Solution {
  public int singleNumber(int[] nums) {
    Set<Integer> set = new HashSet<>();
    for (int i = 0; i < nums.length; i++) {
      if (!set.add(nums[i])) {
        set.remove(nums[i]);
      }
    }
  //返回唯一一个剩下来的值
for (int result : set) { return result; } throw new IllegalArgumentException(); } }

  时间复杂度O(n),空间复杂度O(n)

  3.排序后,双指针,符合题目要求

class Solution {
  public int singleNumber(int[] nums) {
  //快排方式 Arrays.sort(nums); for(int i=0,j=1;j<nums.length;j+=2,i+=2) { if (nums[i]!=nums[j]) { return nums[i]; } } return nums[nums.length-1]; } }

  4.异或操作,目前最优解,不过异或用的比较少,很不熟练

class Solution {
  public int singleNumber(int[] nums) {
    int a=0;
    for(int i=0;i<nums.length;i++) {
      a^=nums[i];
    }
    return a;
  }
}

   时间复杂度O(n),空间复杂度O(1)

posted @ 2019-08-25 16:01  lz_0011  阅读(76)  评论(0编辑  收藏  举报