Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit acc2b03

Browse files
稀疏数组搜索
1 parent 7aca295 commit acc2b03

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.leetcode_cn.easy;
2+
/***********稀疏数组搜索********/
3+
4+
/**
5+
* 稀疏数组搜索。有个排好序的字符串数组,其中散布着一些空字符串,编写一种方法,找出给定字符串的位置。
6+
*
7+
* 示例1:
8+
*
9+
* 输入: words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ta"
10+
* 输出:-1
11+
* 说明: 不存在返回-1。
12+
* 示例2:
13+
*
14+
* 输入:words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ball"
15+
* 输出:4
16+
* 提示:
17+
*
18+
* words的长度在[1, 1000000]之间
19+
*
20+
*/
21+
public class SparseArraySearchLcci {
22+
23+
public static void main(String[] args) {
24+
System.out.println(new SparseArraySearchLcci().findString(new String[]{"at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""}, "ta"));
25+
}
26+
27+
/**
28+
* 二分查找
29+
* @param words
30+
* @param s
31+
* @return
32+
*/
33+
public int findString(String[] words, String s) {
34+
int start = 0;
35+
int end = words.length - 1;
36+
37+
while(start <= end) {
38+
int mid = (start + end) / 2;
39+
int omid = mid;
40+
while(mid >= 0 && words[mid].length() == 0) { // 向左透过空串
41+
mid--;
42+
}
43+
if (mid < 0) return -1;
44+
if (words[mid].compareTo(s) < 0) {
45+
start = omid + 1; // 如果在右边,使用初始mid
46+
} else if (words[mid].compareTo(s) > 0) {
47+
end = mid - 1;
48+
} else {
49+
return mid;
50+
}
51+
}
52+
return -1;
53+
}
54+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /