标签:leetcode 输入 else mamicode 技术 若是 字符串 联系 位置
稀疏数组搜索。有个排好序的字符串数组,其中散布着一些空字符串,编写一种方法,找出给定字符串的位置。
示例1:
输入: words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ta"
输出:-1
说明: 不存在返回-1。
示例2:
输入:words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ball"
输出:4
提示:
words的长度在[1, 1000000]之间
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sparse-array-search-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
采用二分法,若是遇到空字符串则往前寻找,若前面都是空字符串,则往后面寻找。
public int findString(String[] words, String s) { int st = 0; int end = words.length - 1; while (st <= end) { int m = st + ((end - st) >> 1); while ("".equals(words[m])) { m++; if (m > end) { m = st + ((end - st) >> 1); while ("".equals(words[m])) { m--; if (m < st) { return -1; } } } } if (words[m].compareTo(s) == 0) { return m; } if (words[m].compareTo(s) > 0) { end = m - 1; } else { st = m + 1; } } return -1; }
标签:leetcode 输入 else mamicode 技术 若是 字符串 联系 位置
原文地址:https://www.cnblogs.com/wangzaiguli/p/14750758.html