前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode第28/35题

LeetCode第28/35题

作者头像
用户3112896
发布2019-09-26 15:20:52
3970
发布2019-09-26 15:20:52
举报
文章被收录于专栏:安卓圈安卓圈

LeetCode第28题

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

代码语言:javascript
复制
Input: haystack = "hello", needle = "ll"Output: 2

Example 2:

代码语言:javascript
复制
Input: haystack = "aaaaa", needle = "bba"Output: -1

翻译:

返回大字符串中第一次找到给定小字符串的下标

思路:

String有自带API:indexOf

代码:

代码语言:javascript
复制
class Solution {    public int strStr(String haystack, String needle) {        return haystack.indexOf(needle);    }}

我们来看下SDK源码

代码语言:javascript
复制
public int indexOf(String str) {    return indexOf(str, 0);}
public int indexOf(String str, int fromIndex) {    return indexOf(this, str, fromIndex);}
static int indexOf(String source,                   String target,                   int fromIndex) {    if (fromIndex >= source.count) {        return (target.count == 0 ? source.count : -1);    }    if (fromIndex < 0) {        fromIndex = 0;    }    if (target.count == 0) {        return fromIndex;    }
    char first = target.charAt(0);    int max = (source.count - target.count);
    for (int i = fromIndex; i <= max; i++) {        /* Look for first character. */        if (source.charAt(i)!= first) {            while (++i <= max && source.charAt(i) != first);        }
        /* Found first character, now look at the rest of v2 */        if (i <= max) {            int j = i + 1;            int end = j + target.count - 1;            for (int k = 1; j < end && source.charAt(j)                     == target.charAt(k); j++, k++);
            if (j == end) {                /* Found whole string. */                return i;            }        }    }    return -1;}

思路也很简单和暴力,就是遍历对比字符

LeetCode第35题

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

代码语言:javascript
复制
Input: [1,3,5,6], 5Output: 2

Example 2:

代码语言:javascript
复制
Input: [1,3,5,6], 2Output: 1

Example 3:

代码语言:javascript
复制
Input: [1,3,5,6], 7Output: 4

Example 4:

代码语言:javascript
复制
Input: [1,3,5,6], 0Output: 0

翻译:

给定一个有序数组和一个给定值,在数组中找到这个值所在的下标;如果没有这个值,那么返回他应该插入的下标位置

思路:

和选择排序或插入排序思路相似,就是将定值和已经排好序的数组遍历比较大小

代码:

代码语言:javascript
复制
class Solution {    public int searchInsert(int[] nums, int target) {        int j= 0;        for(int i = 0;i<nums.length;i++){            if(nums[i] < target){                j++;            }        }        return j;    }}

如果数组元素比给定值要小,那么J就+1;如果数组元素比给定值要大,J不操作;那么下标比J小的元素值就比给定值要小,即J就是我们所需要的下标

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-05-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 安卓圈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档