一个简单的问题:
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)