1. 程式人生 > >35. Search Insert Position題目和答案詳解

35. Search Insert Position題目和答案詳解

1 題目簡述

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.

您可以在陣列中假設沒有重複。

Example 1:

Input: [1,3,5,6], 5

Output: 2

Example 2:

Input: [1,3,5,6], 2

Output: 1

Example 3:

Input: [1,3,5,6], 7

Output: 4

Example 4:

Input: [1,3,5,6], 0

Output: 0


2 答案詳解

(1) 解決思想

本次解答採用C++編寫,C++相對於C語言的一個重要的特點是:面向物件程式設計(OOP),故我們採用類的方法來實現所述要求。

  首先,假設陣列是按升序排序(降序也類似),且不存在重複的元素。

  然後,遍歷陣列。若遇到比目標大的陣列元素,則返回當前陣列下標(索引)。

  最後,若遍歷完陣列而沒有執行返回操作,則說明目標應放在陣列的最後,所以此時返回陣列的長度即為所要求的下標。

(2) 設計程式

  所設計的程式採用類模板實現,程式如下:

#include <iostream>
#include <vector>
#include <algorithm>

using std::cout;
using std::endl;
using std::vector;

template<class T>
class Solution
{
private:
    const vector<T>& nums_;
    const T& target_;
public:
    Solution(const vector<T>& nums,const T& target):nums_(nums),target_(target) {}
    int SearInsertPos();
};

template<class T>
int Solution<T>::SearInsertPos()
{
    int i;
    for(i = 0; i < nums_.size(); i++) {
        if(nums_[i] >= target_) {
            return i;
        }
    }
    return i;
}

void Display(const int& data)
{
    cout << data << ' ' ;
}

int main()
{
    int arr[] = {1,3,5,6};
    vector<int> nums(arr,arr+4);
    cout << "The array is:" ;
    for_each(nums.begin(),nums.end(),Display);
    Solution<int> sol(nums,5);
    cout << endl << "The target is:" << int(5) << ",The index is:" << sol.SearInsertPos() << endl;
    Solution<int> sol2(nums,2);
    cout << "The target is:" << int(2) << ",The index is:" << sol2.SearInsertPos() << endl;
    Solution<int> sol3(nums,7);
    cout << "The target is:" << int(7) << ",The index is:" << sol3.SearInsertPos() << endl;
    Solution<int> sol4(nums,0);
    cout << "The target is:" << int(0) << ",The index is:" << sol4.SearInsertPos() << endl;
}
程式執行結果為:

The array is:1 3 5 6 

The target is:5,The index is:2
The target is:2,The index is:1
The target is:7,The index is:4
The target is:0,The index is:0