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 }
  • 相关阅读:
    【随笔】新博客
    【Linux】grep命令
    【C/C++】C++11 Move, Forward
    【C/C++】C++11 Variadic Templates
    【C/C++】C++11 Lambda
    【Linux】gdb调试
    【C/C++】数组 & 指针
    【PAT】反转链表
    【OS】Process & Thread
    【Python】Scrapy基础
  • 原文地址:https://www.cnblogs.com/vi3nty/p/7489460.html
Copyright © 2011-2022 走看看