題目: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
這道題比較簡(jiǎn)單。直接貼代碼了荠瘪。
public static int searchInsert(int[] nums, int target) {
int result=-1;
int label=-1;
for(int i=0;i<nums.length;i++)
{
if(nums[i]==target)
{
result=i;
break;
}
if(nums[i]<target)
{
label=i;
}
}
if(result==-1)
{
result=label+1;
}
return result;
}
提交之后發(fā)現(xiàn)還是擊敗了16%的java提交寻馏,仔細(xì)看才發(fā)現(xiàn)秤标,原來(lái)有40%多和我運(yùn)行時(shí)間一樣矮锈。所以感覺這種方法很普通脆丁。接下來(lái)可能要專注更快的解法秃诵,而不是僅僅提交成功就好肥矢,明天可能想想今天和昨天的問(wèn)題的更好解法。ps今天數(shù)學(xué)建模出成績(jī)了符糊,才三等獎(jiǎng)凫海,心碎,失望男娄,但不會(huì)放棄行贪。加油!