2021-07-05算法题

  1. 实现strStr()


    image.png

    思路:暴力匹配:将needle与haystack中所有字串均进行匹配即可

class Solution {
    public int strStr(String haystack, String needle) {
        int index1 = 0;
        int index2 = 0;
        if (needle.length() == 0) {
            return 0;
        } else {
            for (int i = 0; i < haystack.length(); i++) {
                index1 = i;
                while (index1 < haystack.length() && index2 < needle.length()) {
                    if (haystack.charAt(index1) == needle.charAt(index2)) {
                        index1++;
                        index2++;
                    } else {
                        index2 = 0;
                        break;
                    }
                }
                if (index2 == needle.length()) {
                    return i;
                } else if (index1 == haystack.length()) {
                    return -1;
                }
            }
            return -1;
        }
    }
}
  1. 搜索插入位置


    image.png

    思路:当target大于nums[pos]所指元素时pos++,循环结束后的位置即为插入位置(注意在while中要判断pos是否越界)

class Solution {
    public int searchInsert(int[] nums, int target) {
        int pos = 0;
        if (nums.length == 0) {
            nums[0] = target;
            return 0;
        }
        while (target > nums[pos]) {
            pos++;
            if (pos == nums.length) {//注意判断是否越界
                return nums.length ;
            }
        }
        return pos;
    }
}
  1. 最大子序和


    image.png

    思路:

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容