single-number

本文介绍了一种线性时间复杂度的算法,用于从整数数组中找出仅出现一次的元素,而其他元素都出现两次或三次。通过排序和计数,算法能够在不使用额外内存的情况下高效解决问题。

【题目描述】
single-number-i: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?

single-number-ii:
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

【解题思路】题目要求复杂度为O(n),也就是不能在一个n次循环里面添加任何循环,针对这种情况,采用数列排序方法,排序之后就可以很方便地计算一个数在数列中出现了多少次了。一连出现多少次就是总共出现多少次了。
注意考虑特殊情况:

  1. 数列为空
  2. 第一个是single number
  3. 最后一个是single number

【考查内容】数组,复杂度

class Solution {
public:
    int singleNumber(int A[], int n) {
        //特殊情况1,2
		if(n<=0) return -1;
		if(n==1) return A[0];
 
		sort(A, A + n);
		int j = 1;
		for(int i = 0; i < n - 1; i++)
		{
			if(A[i] == A[i+1])
				j++;
			else 
			{
				if(j<2) return A[i];//这里修改为j<3那么就可以适用于single number II了。
 				j = 1;
			}
		}
 
		//特殊情况3 最后一个是single number的特殊情况
		return A[n-1];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值