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.
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

这道题比较简单。直接贴代码了。

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;
    }

提交之后发现还是击败了16%的java提交,仔细看才发现,原来有40%多和我运行时间一样。所以感觉这种方法很普通。接下来可能要专注更快的解法,而不是仅仅提交成功就好,明天可能想想今天和昨天的问题的更好解法。ps今天数学建模出成绩了,才三等奖,心碎,失望,但不会放弃。加油!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容