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:2The target is:2,The index is:1
The target is:7,The index is:4
The target is:0,The index is:0