Code Interview Guide for Coders Chapter 5 Binary Tree Problems

topic

Find string in sorted but empty array

java code

package com.lizhouwei.chapter5;

/**
 * @Description: 在有序但含有空的数组中查找字符串
 * @Author: lizhouwei
 * @CreateDate: 2018/4/24 21:38
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter5_9 {
    public int getIndex(String[] strings, String str) {
        if (strings.length == 0 || str == null) {
            return 0;
        }
        int res = 0;
        int mid = 0;
        int left = 0;
        int temp = 0;
        int right = strings.length - 1;

        while (left < right) {
            mid = (left + right) / 2;
            if (strings[mid] != null && strings[mid].equals(str)) {
                res = mid;
                right = mid - 1;
            } else if (strings[mid] != null) {
                if (strings[mid].compareTo(str) > 0) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } else {
                temp = mid;
                while (strings[temp] == null && --temp >= left) ;
                if (temp < left || strings[temp].compareTo(str) < 0) {
                    left = mid + 1;
                } else {
                    res = strings[temp].equals(str) ? temp : res;
                    right = temp - 1;
                }
            }
        }
        return res;
    }

    //测试
    public static void main(String[] args) {
        Chapter5_9 chapter = new Chapter5_9();
        String[] str = {null, "a", null, "a", null, "b", null, "c"};
        int result = chapter.getIndex(str, "a");
        System.out.println("{null,\"a\",null,\"a\",null,\"b\",null,\"c\"}:");
        System.out.println("字符串a最左的位置为:" + result);
    }
}

result

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324837922&siteId=291194637