只出现一次的数字

题目:

 

 

解:位运算解决;使用集合Set解决

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

 

public int singleNumber(int[] nums) {
   Set<Integer> set = new HashSet<>();
   for (int num : nums) {
       if (!set.add(num)) {
           //如果添加失败,说明这个值
           //在集合Set中存在,我们要
           //把他给移除掉
           set.remove(num);
      }
  }
   //最终集合Set中只有一个元素,我们直接返回
   return (int) set.toArray()[0];
}
 
posted @ 2022-04-22 09:06  仙人掌掌掌掌  阅读(31)  评论(0)    收藏  举报