IT技術小屋

          秋風秋雨,皆入我心

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            38 隨筆 :: 1 文章 :: 19 評論 :: 0 Trackbacks
          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

          本題先對數組進行二分搜索,如果找到了目標元素就返回相應的index,如果最終沒有找到對應的元素,則比較最后一個元素與目標元素的大小。實現代碼如下:
           1 public class Solution {
           2     public int searchInsert(int[] A, int target) {
           3         int length = A.length;
           4         if (A.length == 0) return 0;
           5         int i = 0, j = length - 1;
           6         while (i < j) {
           7             int mid = (i + j) / 2;
           8             if (A[mid] == target) return mid;
           9             if (A[mid] < target) {
          10                 i = mid + 1;
          11             } else {
          12                 j = mid - 1;
          13             }
          14         }
          15         return A[i] < target ? i + 1 : i;
          16     }
          17 }
          posted on 2013-12-23 09:11 Meng Lee 閱讀(103) 評論(0)  編輯  收藏 所屬分類: Leetcode
          主站蜘蛛池模板: 胶南市| 沂源县| 炎陵县| 普洱| 沙河市| 宁武县| 济阳县| 鸡泽县| 云南省| 区。| 阿合奇县| 乐至县| 潞西市| 泗水县| 毕节市| 普兰县| 阿合奇县| 姚安县| 余庆县| 姜堰市| 仙居县| 秦皇岛市| 河东区| 纳雍县| 南京市| 乡城县| 孟津县| 平泉县| 陕西省| 德清县| 萨嘎县| 昌图县| 湖南省| 邵武市| 金门县| 阳西县| 嘉义市| 余干县| 阳山县| 丰城市| 徐州市|