• 11.5 排序后的字符串数组,其中散布着空字符串,编写一个方法,找出给定字符串的位置。


    二分法变体,当查找到mid元素是空串时,同时向两边扩散寻找不为空串的索引作为mid,继续执行二分。

    public class Solution {
    
        public int search(String[] list, String str) {
            if (list == null || list.length == 0 || str == null || str.isEmpty())
                return -1;
            return searchHelper(list, str, 0, list.length - 1);
        }
    
        private int searchHelper(String[] a, String s, int left, int right) {
    
            while (left <= right) {
                int mid = left + (right - left) / 2;
    
                if (a[mid].length() == 0) {
                    int leftNear = mid - 1;
                    int rightNear = mid + 1;
    
                    while (true) {
                        if (leftNear < left && rightNear > right)
                            return -1;
                        if (leftNear >= left && a[leftNear].length() > 0) {
                            mid = leftNear;
                            break;
                        }
                        if (rightNear <= right && a[rightNear].length() > 0) {
                            mid = rightNear;
                            break;
                        }
    
                        leftNear--;
                        rightNear++;
                    }
    
                }
    
                if (a[mid].equals(s))
                    return mid;
    
                else if (a[mid].compareTo(s) < 0) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
    
            }
            return -1;
    
        }
    
        public static void main(String[] args) {
            String[] stringList = { "apple", "", "", "banana", "", "", "", "carrot", "duck", "", "", "eel", "", "flower" };
            System.out.println(new Solution().search(stringList, "carrot"));
        }
    }
  • 相关阅读:
    用C#新建网站的方法
    zhngutils.js
    jQuery源代码学习jQuery对象构建
    前端性能书单
    预则成,不预则废
    表格
    js延时周期执行setTimeout;setInterval;clearTimeout;clearInterval
    url备份
    前端性能集合(各种测试各种资源...)
    Scrum开发模式
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3932748.html
Copyright © 2020-2023  润新知