Sorting&Searching 二分法找有空字符串的数组 @CareerCup

要点是找到最近的不是空字符串的位置,然后作为mid,再继续二分


package Sorting_Searching;

/**
 * Given a sorted array of strings which is interspersed with empty strings,
 * write a method to find the location of a given string.
 * 
 * Example: find “ball” in [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”,“”,
 * “dad”, “”, “”] will return 4
 * 
 * Example: find “ballcar” in [“at”, “”, “”, “”, “”, “ball”, “car”, “”, “”,
 * “dad”, “”, “”] will return -1
 * 
 * 译文:
 * 
 * 给你一个排好序的并且穿插有空字符串的字符串数组,写一个函数找到给定字符串的位置。
 * 
 * 例子:在字符串数组 [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”,“”, “dad”, “”, “”]
 * 中找到"ball",返回下标4.
 * 
 * 例子:在字符串数组 [“at”, “”, “”, “”, “”, “ball”, “car”, “”, “”, “dad”, “”, “”]
 * 中找到"ballcar",查找失败,返回-1.
 * 
 */
public class S11_5 {

	public static void main(String[] args) {
		String[] stringList = { "apple", "", "", "banana", "", "", "",
				"carrot", "duck", "", "", "eel", "", "flower" };
		System.out.println(search(stringList, "apple"));
	}

	public static int search(String[] strings, String str) {
		if (strings == null || str == null || str.isEmpty()) {
			return -1;
		}
		return searchR(strings, str, 0, strings.length - 1);
	}
	
	public static int searchR(String[] strings, String str, int first, int last) {
		if(first > last){
			return -1;
		}
		
		int mid = (first+last)/2;
		
		// 找到离中心最近的不是空字符串的位置
		if(strings[mid].length() == 0 && mid<=last){
			int left = mid-1;
			int right = mid+1;
			while(true){
				if(left<first && right>last){
					return -1;
				}else if(right<=last && strings[right].length()!=0){
					mid = right;
					break;
				}else if(left>=first && strings[left].length()!=0){
					mid = left;
					break;
				}
				right++;
				left--;
			}
		}
		
		if(str.equals(strings[mid])){
			return mid;
		}else if(strings[mid].compareTo(str) > 0){
			return searchR(strings, str, first, mid-1);
		}else {
			return searchR(strings, str, mid+1, last);
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值