只出现一次的数字

题目:

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

说明:

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

示例 1:

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

示例 2:

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

 

我的思路:

方法一:用map来存,map的value为1的值取出来即可

方法二:用一个set来存,然后将set内的每个元素数量变为原来两倍,接着减去原数组内的元素,剩下的那个元素即是

方法三:两个for循环来遍历判断

class Solution {
    public int singleNumber(int[] nums) {
        int res = 0;
        int count = 1;
        for (int i = 0; i < nums.length; i++){
            count = 1;
            for (int j = 0 ; j < nums.length; j++){
                if (nums[i] == nums[j] && i != j ){
                    count++;
                }
            }
            System.out.println("count: "+count);
            System.out.println("nums[i]: "+nums[i]);
            if(count == 1){
                return res = nums[i];
            }
        }
        return res;
    }
}

两个for跑下来很慢

 

参考一下他人的做法:

方法一:

很吊,用异或来获取唯一的那个值

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

 

方法二:

实现一个快速排序,调用快排,两两对比,出现不同即返回后一个元素。

class Solution {
    public int singleNumber(int[] nums) {
        QuickSort(nums, 0, nums.length-1);
		int currentElement=nums[0];
		for(int i=1;i<nums.length;i++){
			if(currentElement==nums[i])
				{i++;
				currentElement=nums[i];}
			else{
				return currentElement;
			}
		}
		return currentElement;
    }
    public  void QuickSort(int[] a, int left, int right) {
		// 如果left等于right,即数组只有一个元素,直接返回
		if (left >= right) {
			return;
		}
		// 设置最左边的元素为基准值
		int key = a[left];
		// 数组中比key小的放在左边,比key大的放在右边,key值下标为i
		int i = left;
		int j = right;
		while (i < j) {
			// j向左移,直到遇到比key小的值
			while (a[j] >= key && i < j) {
				j--;
			}
			// i向右移,直到遇到比key大的值
			while (a[i] <= key && i < j) {
				i++;
			}
			// i和j指向的元素交换
			if (i < j) {
				int temp = a[i];
				a[i] = a[j];
				a[j] = temp;
			}
		}
		a[left] = a[i];
		a[i] = key;
		QuickSort(a, left, i - 1);
		QuickSort(a, i + 1, right);
	}
}

方法三:

和上方法一致,调用Arrays.sort()

class Solution {
    public int singleNumber(int[] nums) {
        Arrays.sort(nums);
        int number= nums.length;
        if(number==1) return nums[0];
        int i=0;
           while(nums[i]==nums[i+1]){
               i+=2;
               if(i>=(number-1))return  nums[i];
           }
        return nums[i];
        
    }
}

 

转载于:https://my.oschina.net/u/3973880/blog/2207988

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值