【LeetCode-面接アルゴリズムクラシック-Java実装】【035-Search Insert Position(挿入位置検索)】


【035-Search Insert Position(挿入位置検索)】
【LeetCode-面接アルゴリズムクラシック-Java実装】【すべてのテーマディレクトリインデックス】
原題
  Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.   You may assume no duplicates in the array.   Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

テーマの大意
ソート配列と指定した値を指定し、この値が見つかったら、この値の位置を返し、見つからなかったら、この値の配列内の挿入位置を返します.配列に重複する要素がないと仮定します.
問題を解く構想.
一、最も直接的な検索アルゴリズムで、左から右へ検索します.二、二分検索アルゴリズムを使用する.
コード実装
アルゴリズム実装クラス(直接検索)
public class Solution {
    public int searchInsert(int[] A, int target) {

        if (A == null) {
            return -1;
        }

        int i;
        for (i = 0; i < A.length; i++) {
            if (A[i] >= target) {
                return i;
            }
        }

        return i;
    }
}

アルゴリズム実装クラス(二分検索)
public class Solution {
    public int searchInsert(int[] A, int target) {

        int mid;
        int lo = 0;
        int hi = A.length - 1;

        while (lo <= hi) {
            mid = lo + (hi - lo)/ 2;

            if (A[mid] == target) {
                return mid;
            } else if (A[mid] < target){
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }

        return lo;
    }
}

評価結果
画像をクリックすると、マウスは解放されず、位置をドラッグして、解放された後、新しいウィンドウで完全な画像を表示します.
ちょくせつアルゴリズム
にぶんたんさくアルゴリズム
特別説明
転載を歓迎します.転載は出典を明記してください.http://blog.csdn.net/derrantcm/article/details/47079367】