leetcode:剑指offer----数组中重复的数字

题目:

在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

示例1:

[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3 

解题方法:

  • C++解决

利用C++的STL中的set或者unordered_set不允许重复值的特性来解决。通过名字可以看出来,set内部的数据是有序的,unordered_set内部的数据为无序,所以在不需要排序时,unorder_set会比set的效果好。

#include <iostream>
#include <set>
#include <unordered_set>

int main()
{
    set<int> orderSet;
    unordered_set<int> unorderSet;

    //返回set容器中的第一个元素
    int begin = orderSet.begin();
    //返回set容器中的最后一个元素
    int end = orderSet.end();
    //删除set容器中的所有元素
    orderSet.clear();
    //判断容器是否为空
    bool isEmpty = orderSet.empty();
    //返回set容器中的元素个数
    int size = orderSet.size();
    //返回一个指向被查到元素的迭代器
    set<int>::iterator it;
    it = orderSet.find(target);
    //向set容器中添加一个元素
    orderSet.insert(5);

    return 0;
}
  • python解决

python中同样利用set集合来实现该问题

def findRepeatNumber(nums):
    s = set()
    for num in nums:
        #得到set集合内部元素格式
        length = len(s)
        #往set集合中添加元素
        s.add(num)
        if len(s) == length:
            return num
        else:
            continue
    return None

猜你喜欢

转载自blog.csdn.net/qq_25105061/article/details/120733448
今日推荐