【c++】面试题3 数组中重复的数字


思路总结:
每一次将不合适numbers[i]换到自己的位置去,也就是每次遍历会有一个位置归为成功,如果要去的位置已经有了相匹配的数字,说明重复。

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) {
        if(numbers == nullptr || length < 0)
            return false;
        for(int i = 0;i < length; i++){
            if(numbers[i] >= length || numbers[i] < 0)
                return false;
        }
        for(int i = 0; i < length; i++){
            while(i != numbers[i]){
                if(numbers[i] == numbers[numbers[i]]){
                    *duplication = numbers[i];
                    return true;
                }
                int tmp = numbers[i];
                numbers[i] = numbers[tmp];
                numbers[tmp] = tmp;
            }
            
        }
        return false;
    }
};
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) {
        int i = 0;
        while(i < length){
            int value = numbers[i];
            if(value == i){
                i++;
                continue;
            }
            if(numbers[value] == value){
                *duplication =  value;
                return true;
            }
            else{
                swap(numbers[i], numbers[value]);
                continue;
            }
            i++;
        }
        return false;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容