leetcode算法——136. Single Number(基于JAVA)

4 篇文章 0 订阅
3 篇文章 0 订阅

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?


翻译:

给定一个整数数组,每个元素出现两次除了一个,请找到那一数。

注意:

你的算法运行时应该有一个线性的复杂性。你能实现它不使用额外的内存吗?


解题思路1:

首先分析这个题目发现需要注意,所有的数都会出现2次,除了一个,但是并没有说这个数是出现了几次,所以那个single number出现的次数只是不等于2而已。在没有考虑他的额外要求时,很简单很单纯的就是使用2层for循环对数组中所有数字的出现次数计数,最后判断次数不等于2的就是那个single number。

这个解法太没技术含量,但是能够满足基本要求。

public int singleNumber(int[] nums) {
        int len = nums.length;
        int count []= new int[len];
        for(int i = 0; i < len; i++){
        	for(int j = 0; j < len; j++){
        		if(nums[i] == nums[j]){		
        			count[i]++;
        		}
        	}
        	if(count[i] != 2){
        		return nums[i];
        	}
        }  
        return 0;
    }

具体情况如下:



解题思路2:后面找了别人的代码,发现一个很简单的方法:异或
参考代码的核心思路就是运用了 <两个相同的数进行按位异或运算结果一定为0,一个数与0按位异或结果即为该数本身>,所以讲数组中所有数按位异或,留下的那个数即是那个single number。
 public int singleNumber(int[] nums) {
        int res = 0;
        for(int i = 0; i < nums.length; i++){
          res ^= nums[i];
        }
        return res;
    }

具体情况如下:


解题思路3:还有一种类似的:

if (nums == null || nums.length < 1) {
            throw new IllegalArgumentException("nums");
        }
        for (int i = 1; i< nums.length; i++) {
            nums[0] ^= nums[i];
        }
        return nums[0];
具体情况如下:





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值