• 剑指offer


    一、数组

    1. 数组中重复的数字

    题目描述:

    ​ 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

    思路:哈希

    ​ 时间复杂度O(n),空间复杂度O(n)

    代码:

    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 hashTable[length];
            for(int i=0;i<length;i++){
                hashTable[i]=0;
            }
            for(int i=0;i<length;i++){
                hashTable[numbers[i]]+=1;
                if(hashTable[numbers[i]]>1){
                    *duplication=numbers[i];
                    return true;
                }
            }
            return false;
        }
    };
    

    【注意】使用变量定义数组长度时,不要在定义的同时进行初始化赋值,要在之后进行赋值。

    即上面在开哈希数组的时候,不要写成int hashTable[length]={0};

    2. 二维数组中的查找

    题目描述:

    ​ 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

    思路:二分查找

    ​ 遍历每一行,对每一行进行一次二分查找。时间复杂度O(nlogn),空间复杂度O(1)

    代码:

    class Solution {
    public:
        bool Find(int target, vector<vector<int> > array) {
            for(int i=0;i<array.size();i++){
                int low=0;
                int high=array[i].size()-1;
                while(low<=high){
                    int mid=(low+high)/2;
                    if(target<array[i][mid]){
                        high=mid-1;
                    }else if(target>array[i][mid]){
                        low=mid+1;
                    }else{
                        return true;
                    }
                }
            }
            return false;
        }
    };
    
  • 相关阅读:
    oracle 查找或删除重复记录的语句
    多线程案例
    JAVA调用增删改的存储过程
    设计中最常用的CSS选择器
    ORACLE多表查询优化
    oracle存储过程的事务处理
    oracle函数调用存储过程
    oracle存储过程的基本语法
    java.lang.OutOfMemoryError: Java heap space解决方法
    文件操作工具类
  • 原文地址:https://www.cnblogs.com/jiajun107/p/12310879.html
Copyright © 2020-2023  润新知