ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

算法刷题手记3

2022-05-18 13:33:37  阅读:29  来源: 互联网

标签:arr right int list mid 算法 手记 刷题 left


描述

二分查找扩展:如果数组有序,且存在多个目标值,查询所有目标值索引返回。

public class Main {

    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        int[] arr = {1, 2, 2, 2, 3, 4, 5, 6, 7};
        List list1 = binarySearch(arr, 0, arr.length, 2, list);
        System.out.println(Arrays.toString(list1.toArray()));

    }

    public static List<Integer> binarySearch(int[] arr, int left, int right, int findVal, List<Integer> list) {
        int mid = (left + right) / 2;
        int midVal = arr[mid];

        if (findVal < midVal) {
            right = mid - 1;
            return binarySearch(arr, left, right, findVal, list);
        } else if (findVal > midVal) {
            left = mid + 1;
            return binarySearch(arr, left, right, findVal, list);
        } else {
            left = mid - 1;
            while (left >= 0) {
                if (arr[left] != findVal) {
                    break;
                }
                list.add(left);
                left--;
            }
            list.add(mid);
            right = mid + 1;
            while (right < arr.length) {
                if (arr[right] != findVal) {
                    break;
                }
                list.add(right);
                right++;
            }
            return list;
        }
    }
    
}

 

标签:arr,right,int,list,mid,算法,手记,刷题,left
来源: https://www.cnblogs.com/sun-10387834/p/16284330.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有