LeetCode-搜尋插入位置

來源:互聯網
上載者:User

標籤:||   alc   oca   content   位置   outline   ash   gnuplot   apt   

LeetCode-搜尋插入位置Table of Contents
  • 1. Easy-搜尋插入位置
    • 1.1. 題目描述
    • 1.2. 樣本 1:
    • 1.3. 樣本 2:
    • 1.4. 樣本 3:
    • 1.5. 樣本 4:
  • 2. 自己的解答
    • 2.1. 思路
    • 2.2. 代碼
1 Easy-搜尋插入位置1.1 題目描述

給定一個排序數組和一個目標值,在數組中找到目標值,並返回其索引。如果目標值不存在於數組中,返回它將會被按順序插入的位置。

你可以假設數組中無重複元素。

1.2 樣本 1:

輸入: [1,3,5,6], 5

輸出: 2

1.3 樣本 2:

輸入: [1,3,5,6], 2

輸出: 1

1.4 樣本 3:

輸入: [1,3,5,6], 7

輸出: 4

1.5 樣本 4:

輸入: [1,3,5,6], 0

輸出: 0

2 自己的解答2.1 思路
  1. 使用二分尋找法尋找插入的位置.
  2. 定義了三個變數,start,end,mid,分別表示開始尋找索引的起始位置,中間位置和末尾位置.
  3. 遍曆的條件為start小於等於end.傳回值為start
  4. 如果數組中不存在target,則會遍曆到start和end相等的情況時候,mid同樣也在start處
  5. 如果target大於nums[mid],插入位置在start後,start會自動加1,同樣結束了迴圈.
  6. 如果target小於nums[mid],插入位置在,插入在同樣在start處,此時只是對end-1,同樣結束了迴圈.
2.2 代碼
package algorithm.easy;public class SearchInsert {    public static int solution(int[] nums, int target) {        if (nums == null || nums.length < 1)            return 0;        // 使用二分尋找法        int start = 0;        int end = nums.length - 1;        int mid = 0;        // 如果數組中不存在target,則會遍曆到start和end相等的情況時候,mid同樣也在start處        // 如果target大於nums[mid],插入位置在start後,start會自動加1,同樣結束了迴圈.        // 如果target小於nums[mid],插入位置在,插入在同樣在start處,此時只是對end-1,同樣結束了迴圈.        while (start <= end) {            // 中間元素是start和mid相加,mid是起始元素的索引+start到end長度的一半            mid = start + (end - start)/ 2;            if (target < nums[mid]) {                end = mid - 1;            } else if (target > nums[mid]){                start = mid + 1;            } else {                return mid;            }        }        return start;    }    public static void main(String[] args) {        int[] test = {1,3,4,6};        int[] test2 = {1,3,5,7,8,9,11};        int [] test3 = {1,3};        System.out.println(solution(test,5));//        System.out.println(solution(test2,12));    }}

Date: 2018-11-02 23:07

Author: devinkin

Created: 2018-11-02 五 23:07

Validate

LeetCode-搜尋插入位置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.