zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第五章 字符串问题 在有序但含有空的数组中查找字符串

    题目

    在有序但含有空的数组中查找字符串

    java代码

    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);
        }
    }
    
    

    结果

  • 相关阅读:
    SpringMVC的下载
    上传的前台实现
    SpringMVC自定义视图解析器的使用
    SpringMVC的Model对象的使用
    SpringMVC中使用作用域对象完成数据的流转
    SpringMVC的响应介绍
    SpringMVC的静态资源放行配置
    SpringMVC的静态资源放行
    SpringMVC的编码过滤器配置
    pymysql
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8934123.html
Copyright © 2011-2022 走看看