编程练习【稀疏数组搜索】

稀疏数组搜索。有个排好序的字符串数组,其中散布着一些空字符串,编写一种方法,找出给定字符串的位置。

示例1:

 输入: words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ta"
 输出:-1
 说明: 不存在返回-1。
示例2:

 输入:words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ball"
 输出:4

题目来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sparse-array-search-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

方法一:暴力搜索

直接循环遍历数组返回索引。

代码:

public static int findString(String[] words, String s) {
		for (int i = 0; i < words.length; i++) {
		    if(s.equals(words[i])) {
		    	return i;
		    }
		}
		return -1;
    }

 方法二:二分查找法

分别记录数组的最左边和最右边的索引,遇到空字符串时将两个指针分别向前向后移动,然后根据二分查找的方式来找到目标字符串。

代码:

public static int findString(String[] words, String s) {
		int len = words.length;
		int l = 0;
		int r = len - 1;
		while (l <= r) {
			while (l <= r && words[l].equals(""))
				l++;
			while (l <= r && words[r].equals(""))
				r--;
			int mid = l + (r - 1) / 2;
			while (mid <= r && words[mid].equals(""))
				mid++;
			if (words[mid].compareTo(s) == 0) {
				return mid;
			}
			if (words[mid].compareTo(s) > 0) {
				r = mid - 1;
			} else {
				l = mid + 1;
			}
		}
		return -1;
	}

你可能感兴趣的:(java编程练习,java,算法,开发语言)