力扣(LeetCode) 35. 搜索插入位置


給定一個排序數組和一個目標值,在數組中找到目標值,並返回其索引。如果目標值不存在於數組中,返回它將會被按順序插入的位置。

你可以假設數組中無重復元素。

示例 1:

輸入: [1,3,5,6], 5
輸出: 2

示例 2:

輸入: [1,3,5,6], 2
輸出: 1

示例 3:

輸入: [1,3,5,6], 7
輸出: 4

示例 4:

輸入: [1,3,5,6], 0
輸出: 0

Java版

class Solution {
    public int searchInsert(int[] nums, int target) {
		int[] res =  new int[nums.length+1];
        int i=0;
		for(i=0;i<nums.length;i++) {
			res[i]=nums[i];
		}
		res[res.length-1]=target;
		Arrays.sort(res);
		for(i=0;i<res.length;i++) {
			if(res[i]==target) {
				break;
			}
		}
        return i;
    }
}

精簡版

class Solution {
    public int searchInsert(int[] nums, int target) {
		for(int i=0;i<nums.length;i++) {
			if(target<=nums[i]) {
				return i;
			}
		}
        return nums.length;
    }
}

運行結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM