• 数组中重复的数字问题


    如题所述,这类问题出现的频率太高了,有必要进行归纳归纳~

    --->给定一个长度为N的数组,其中每个元素的取值范围都是1到N。判断数组中是否有重复的数字。(原数组不必保留)

    方法1.
    对数组进行排序(快速,堆),然后比较相邻的元素是否相同。
    时间复杂度为O(nlogn),空间复杂度为O(1)。

    方法2.
    使用bitmap方法。
    定义长度为N/8的char数组,每个bit表示对应数字是否出现过。遍历数组,使用 bitmap对数字是否出现进行统计。
    时间复杂度为O(n),空间复杂度为O(n)。

    方法3.
    遍历数组,假设第 i 个位置的数字为 j ,则通过交换将 j 换到下标为 j 的位置上。直到所有数字都出现在自己对应的下标处,或发生了冲突。
    时间复杂度为O(n),空间复杂度为O(1)。

    示例代码:

    剑指offer练习题

    class Solution {
    public:
        // Parameters:
        //        numbers:     an array of integers
        //        length:      the length of array numbers
        //        duplication: (Output) the duplicated number in the array number
        // Return value:       true if the input is valid, and there are some duplications in the array number
        //                     otherwise false
        bool duplicate(int numbers[], int length, int* duplication) {
            //思路:遍历数组,假设第 i 个位置的数字为 j ,则通过交换将 j 换到下标为 j 的位置上。
            //直到所有数字都出现在自己对应的下标处,或发生了冲突。
            //ps:由于长度为n的数组里的所有数字都在0到n-1的范围内,所以不需要扩展额外的空间
            for(int i=0;i<length;i++){
                if(numbers[i]!=i){
                    if(numbers[i]!=numbers[numbers[i]])
                        swap(numbers[i],numbers[numbers[i]]);
                    else{
                        *duplication=numbers[i];
                        return true;
                    }
                }
            }
            return false;
        }
    };
    

      

  • 相关阅读:
    wcf简单的创建和运用
    关于DevExpress的gridControl的简单使用
    泛型 Field 和 SetField 方法 (LINQ to DataSet)
    【转】string.Format对C#字符串格式化
    ashx实现文件下载以及文件MD5码测试
    【转】10分钟了解设计模式(C#)
    [转]Jquery中AJAX错误信息调试参考
    搭建Harbor docker镜像仓库
    安装python3.x
    shell替换
  • 原文地址:https://www.cnblogs.com/carsonzhu/p/5425021.html
Copyright © 2020-2023  润新知