美文网首页
Search Insert Position

Search Insert Position

作者: 小明今晚加班 | 来源:发表于2019-02-20 19:50 被阅读0次
题目描述:

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
分析:给定一个有序的数组和要查询的目标值target,返回该目标值在数组中的下标index;如果数组中没有target的话,请返回target在数组中应该占据的下标index。

我的Code如下:

class Solution {
    public int searchInsert(int[] nums, int target) {
        int index = 0;
        if(nums.length == 0){
            return index;
        }
        
        //解决target存在于nums数组中的情况
        for(int i =0;i<nums.length; i++){
            if(nums[i]==target){
                return i;
            }
        }
        
        //解决target不存在与nums数组中的情况
        for(int i=0;i<nums.length;i++){            
            if(target<nums[i]){
                return i;
            }
            //下面这个判断是为了解决特殊状况:nums=[0], target=1
            if(i==nums.length-1){
                return i+1;
            }
        }
        return index;
    }
}

相关文章

网友评论

      本文标题:Search Insert Position

      本文链接:https://www.haomeiwen.com/subject/bulkyqtx.html