LeetCode 961: N-Repeated Element in Size 2N Array解法汇总

这篇博客汇总了解决LeetCode第961题的多种方法,包括C++, Java和Python的实现。作者指出,通过从每个元素的后一个位置开始搜索,可以降低时间复杂度。此外,还提到了一种特定的序列性质:存在一个包含重复元素的长度为4的子序列。" 86544518,7982108,SQLServer 2008分区表操作实践:创建与管理,"['数据库管理', 'SQLServer', '分区技术']
摘要由CSDN通过智能技术生成


更多LeetCode题解

力扣中文网没有此题

My Solution

此题很简单,要注意的是对每一个元素的搜索,只要从它的后一个元素开始搜索就可以了,减少一些时间复杂度

C++

class Solution {
public:
	int repeatedNTimes(vector<int>& A) {
		int res;
		for (int i = 0; i < A.size() - 1; i++) {
			if (find(A.begin() + i + 1, A.end(), A[i]) != A.end()) {
				res = A[i];
				break;
			}
		}
		return res;
	}
};

通过容器,来调用容器的count方法,很方便,C++的unordered_map也有类似的功能。

java

class Solution {
    public int repeatedNTimes(int[] A) {
        Map<Integer, Integer> count = new HashMap();
        for (int x: A) {
            count.put(x, count.getOrDefault(x, 0) + 1);
        }

        for (int k: count.keySet())
            if (count.get(k) > 1)
                return k;

        throw null;
    }
}

python

class Solution(object):
    def repeatedNTimes(self, A):
        count = collections.Counter(A)
        for k in count:
            if count[k] > 1:
                return k

Approach 2

此序列满足:
必存在一个长度为4的子序列,子序列内有重复元素。

java

class Solution {
    public int repeatedNTimes(int[] A) {
        for (int k = 1; k <= 3; ++k)
            for (int i = 0; i < A.length - k; ++i)
                if (A[i] == A[i+k])
                    return A[i];

        throw null;
    }
}

python

class Solution(object):
    def repeatedNTimes(self, A):
        for k in xrange(1, 4):
            for i in xrange(len(A) - k):
                if A[i] == A[i+k]:
                    return A[i]
class Solution:
    def repeatedNTimes(self, A):
        for i in range(len(A)):
            if A[i - 1] == A[i] or A[i - 2] == A[i]:
                return A[i]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值