zoukankan      html  css  js  c++  java
  • 搜索算法

    搜索往往是建立在排好序的基础上的
    二分查找

    public class BinarySearch {
        public int search(int[] nums, int target) {
            int n = nums.length;
            int i = 0, j = n, m;
            while (i < j) {
                m = i + (j - i) / 2;
                if (nums[m] == target) {
                    return m;
                } else if (nums[m] < target) {
                    i = m + 1;
                } else {
                    j = m;
                }
            }
            return -1;
        }
    }
    
    public class TestBinarySearch {
        public static void main(String[] args) {
            int[] a = {0,1,2,3,4,5,6,7,8,9};
            int target = (int)(15*Math.random());
            System.out.println(target);
            System.out.println(binarySearch(a,target));
        }
    
        public static int binarySearch(int[] a,int target){
            int i = 0,j = a.length-1,mid;
            while (i<=j){
                mid = i + (j-i)/2;
                if (a[mid] == target){
                    return mid;
                } else if (a[mid] < target){
                    i = mid + 1;
                } else {
                    j = mid - 1;
                }
            }
            return -1;
        }
    }
    
  • 相关阅读:
    【转】数学题目大集合
    hdu3534,个人认为很经典的树形dp
    GYM
    HDU
    POJ
    POJ
    POJ
    set的经典应用
    天梯赛训练1 7-9 集合相似度
    天梯赛训练1 7-8 查验身份证
  • 原文地址:https://www.cnblogs.com/hgnulb/p/11371008.html
Copyright © 2011-2022 走看看