程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode題解:Search Insert Position

LeetCode題解:Search Insert Position

編輯:C++入門知識

LeetCode題解:Search Insert Position


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[] nums, int target) {
        int count = nums.length;
        int left = 0;
        int step = 0;
        int mid = 0;

        while(count > 0){
            step = count >> 2;
            mid = left + step;

            if(nums[mid] < target){
                left = mid + 1;
                count -= (step + 1);
            }else{
                count = step;
            }
        }

        return left;
    }
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved