35. Search Insert Position

来源:互联网 发布:java 静态单例模式 编辑:程序博客网 时间:2024/05/29 11:53

35. 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

翻译

给定排序的数组和目标值,如果找到目标,返回索引。如果没有,如果按顺序插入索引就返回索引。

您可以假定阵列中没有重复项。

这里有几个例子。
[1,3,5,6],5→2,2
[1,3,5,6]→
[1,3,5,6]1,7→
[1,3,5,6]4,0→0

解题思路

public class Solution {    public int searchInsert(int[] nums, int target) {        if(target>nums[nums.length-1])            return nums.length;        int location=0;        for(int i=0;i<nums.length;i++){            if(nums[i]>=target){                location=i;                break;            }        }        return location;    }}

欢迎加入中科院开源软件自习室:631696396

欢迎加入中科院开源软件自习室