1. 程式人生 > >Leetcode34. Find First and Last Position of Element in Sorted Array

Leetcode34. Find First and Last Position of Element in Sorted Array

描述:

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

解題思路:

本題的解法是將vector中的每一個元素與target進行比對,當元素與target相等時將下標記錄下來。

C++程式碼:

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) 
    {
        vector<int>res;
        vector<int>result;
        vector
<int>
res_copy(2,-1); int len= nums.size(); for(int i = 0;i<len;i++) { if(nums[i]==target) { res.push_back(i); } } if(res.size()==0) { return res_copy; } if(res.size()==1
) { res.push_back(res[0]); return res; } if(res.size()==2) { return res; } if(res.size()>2) { result.push_back(res[0]); result.push_back(res[res.size()-1]); return result; } return res; } };

執行結果:

這裡寫圖片描述
這裡寫圖片描述