码迷,mamicode.com
首页 > 其他好文 > 详细

Search Insert Position

时间:2014-11-05 12:20:59      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   for   sp   div   

一个简单的问题:

c++

#include<iostream>
using namespace std;

int searchInsert(int a[],int n,int target){
    int i ,count;
    if (target< a[0]){
        count = 0;
        return count;
    }
    if (target>a[n-1]){
        count= n;
        return count;
    }
    for (i=0;i<n-1;++i){
        if (target > a[i] && target < a[i+1]){
            count = i+1;
        }
    }
    for (i=0; i<n ; ++i){
        if (target==a[i]){
            count=i;
        }
    }
    return count;
}

 

还有更简洁的:

python

class Solution:
    # @param A, a list of integers
    # @param target, an integer to be inserted
    # @return integer
    def searchInsert(self, A, target):
        A=A+[target]
        A.sort()
        return A.index(target)

 

Search Insert Position

标签:style   blog   io   color   ar   os   for   sp   div   

原文地址:http://www.cnblogs.com/iois/p/4075681.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!