136. Single Number

本文介绍了一种线性时间复杂度且常数空间复杂度的方法来找出数组中仅有的单例元素。利用异或操作的独特性质,实现了高效查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

136. Single Number

Discuss  Pick One

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?

题意:

一组数组,所有的数字都是成对出现的,只有一个数字是单独出现的,找到单独出现的数组
空间复杂度要求为常数,时间复杂度为线性

算法思路:

异或操作的原理是相同的数为0,不同的数为其本书,所有把所有的数依次按位异或,最终剩下的数就是单独的那个数

代码:

package easy;

public class SingleNumber {
	public int singleNumber(int[] nums) {
		
        int result = 0;
        
        for(int i=0; i<nums.length; i++){
        	result ^= nums[i];
        }
        
        return result;
    }
	
	public static void main(String[] args){
		System.out.println(3^1);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值