zoukankan      html  css  js  c++  java
  • LeetCode记录之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
    [1,3,5,6],2→1
    [1,3,5,6],7→4
    [1,3,5,6],0→0


     1 class Solution {
     2     public int searchInsert(int[] nums, int target) {
     3         int k=0;
     4         if(target>nums[nums.length-1])
     5             return nums.length;
     6         if(target<nums[0])
     7             return 0;
     8         else{
     9             for(int i=0;i<nums.length-1;i++){
    10                 if(nums[i]==target&&target<nums[i+1]){
    11                     k=i;
    12                     break;
    13                 }
    14                 if(nums[i]<target&&target<=nums[i+1]){
    15                     k=i+1;
    16                     break;
    17                 }
    18             }
    19         }
    20         return k;
    21     }
    22 }
  • 相关阅读:
    web Function函数
    web语言发展史
    用户正则
    字符串替换
    css单位
    JavaScript DOM&BOM
    css颜色的设置
    pseudo-class与pseudo-element的不同点与相同点
    对css语法中position值的理解
    API
  • 原文地址:https://www.cnblogs.com/xpang0/p/7489460.html
Copyright © 2011-2022 走看看