剑指offer-算法和数据操作——排序、查找与回溯

算法和数据操作——排序、查找与回溯

排序与查找

旋转数组的最小数字

题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

思路分析:本题如果使用二分查找的思路,那么时间复杂度为O(n),没有用到数组是旋转数组的特性,本题中如果使用二分查找的话可以在O(logn)的时间复杂度内完成查找。

像一般的二分查找,使用三个数组下标index1指向数组的头,index2指向数组的尾部,indexmid指向数组的中间位置。如果indexmid指向的数据大于或者等于index1指向的数据,那么根据旋转数组的特性可以得知最小的数据在数组的后半部分,如果indexmid指向的数据小于或者等于index2指向的数据,那么最小的数据应该在前半部分。根据这样的思路一致查找,最终index1会指向数组中最大的数据,index2会指向数组中最小的数据,此时index2与index1相差1。但是如果index1,indexmid, index2三者指向的数据是一样的时候就无法判断了,比如数组1 1 1 0 1 1,在第一轮的时候index1,indexmid,index2指向的数据都是1,按照上述的判断思路,我们无法判定indexmid指向的1是属于第一个递增子数组还是属于第二个递增子数组,在这中情况下需要使用顺序查找来找到最小的数字,时间复杂度为O(n)。

class Solution {
public:
    int minNumberInRotateArray(vector<int> rotateArray) {
        int size = rotateArray.size();
        if (size == 0) return 0;
        int index1 = 0;
        int index2 = size - 1;
        int indexmid = 0;
        while (rotateArray[index1] >= rotateArray[index2]) {
            if (index2 - index1 == 1) {
                // 两个下标相差1表明已经找到了最小的数字
                indexmid = index2;
                break;
            }
            indexmid = (index1 + index2) / 2;

            //如果index1,index2,和indexmid指向的数据相等,那么使用顺序查找
            //因为这个时候无法根据这几个数据的大小判断数组的排序情况
            if (rotateArray[index1] == rotateArray[indexmid] 
                && rotateArray[indexmid] == rotateArray[index2]) {
                return MinInOrder(rotateArray);
            }
            if (rotateArray[indexmid] >= rotateArray[index1]) {
                index1 = indexmid;
            } else if (rotateArray[indexmid] <= rotateArray[index2]) {
                index2 = indexmid;
            }
        }
        return rotateArray[indexmid];
    }

    int MinInOrder(vector<int> vec) {
        //  顺序查找最小的数字
        int size = vec.size();
        int min = 0;
        for (int i = 0; i < size; i++) {
            if (min < vec[i])
                min = vec[i];
        }
        return min;
    }
};

回溯法

矩阵中的路径

题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

class Solution {
public:
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
        if (matrix == nullptr || rows < 1 || cols < 1 || str == nullptr)
            return false;
        
        int row = 0;
        int col = 0;
        int pathlength = 0;
        bool* visited = new bool[rows * cols];
        memset(visited, 0, rows*cols);
        for (row = 0; row < rows; row++) {
            for (col = 0; col < cols; col++) {
                //  从字符矩阵的左上角开始,以任何一个节点作为初始的节点,直到找到路径或者遍历完整个数组为止
                if (HasPath(matrix, rows, cols, row, col, pathlength, str, visited))
                    return true;
            }
        }

        delete []visited;
        return false;
    }

    bool HasPath(const char* matrix, int rows, int cols, int row, int col, int& pathlength, const char* str, bool* visited) {
        if (str[pathlength] == '\0')
            return true;
            //  此判断条件表明已经找到了一条路径;

        bool haspath = false;
        if (row >= 0 && row < rows && col >= 0 && col < cols 
            && matrix[row * cols + col] == str[pathlength] 
            && !visited[row * cols + col]) {
                //  当前位置的字符与要找的字符匹配,并且在字符矩阵中字符并没有被访问过。
                ++pathlength;
                visited[row * cols + col] = true;
                // 以当前节点为圆心分别向当前节点的四周寻找路径,看看路径是否存在,
                //  使用这种方法找出来的路径可能不止一条
                haspath = HasPath(matrix, rows, cols, row - 1, col, pathlength, str, visited)
                          || HasPath(matrix, rows, cols, row + 1, col, pathlength, str, visited)
                          || HasPath(matrix, rows, cols, row, col - 1, pathlength, str, visited)
                          || HasPath(matrix, rows, cols, row, col + 1, pathlength, str, visited);
                
                if (!haspath) {
                    //  如果没有找到路径那么回溯到上一个节点。
                    visited[row * cols + col] = false;
                    --pathlength;
                }
        }
        return haspath;
    }
};

机器人的运动范围

题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

class Solution {
public:
    int movingCount(int threshold, int rows, int cols) {
        if (threshold < 0 || rows < 1 || cols < 1)
            return 0;
        bool* visited = new bool[rows * cols];
        memset(visited, 0, rows * cols);
        
        int count = 0;
        count = movingCheckCount(threshold, rows, cols, 0, 0, visited);
        return count;
    }

    int movingCheckCount(const int threshold, const int rows, const int cols, 
                            int row, int col, bool* visited) {
        int count = 0;
        if (Check(threshold, rows, cols, row, col, visited)) {
            visited[row * cols + col] = true;
            count = 1 + movingCheckCount(threshold, rows, cols, row - 1, col, visited)
                      + movingCheckCount(threshold, rows, cols, row + 1, col, visited)
                      + movingCheckCount(threshold, rows, cols, row, col - 1, visited)
                      + movingCheckCount(threshold, rows, cols, row, col + 1, visited);
        }
        return count;
    }

    bool Check(const int threshold, const int rows, const int cols, 
                int row, int col,  bool* visited) {
        if (threshold < 0 || row < 0 || row >= rows || col < 0 
            || col >= cols || visited[row * cols + col] == true) {
            return false;
        }
        int num = 0;
        int ro = row, co = col;
        while (ro > 0) {
            num += ro % 10;
            ro = ro / 10;
        }
        while (co > 0) {
            num += co % 10;
            co = co / 10;
        }
        if (num > threshold)
            return false;
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值