LeetCode——搜索插入位置
题目描述:
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。
如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 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
解题思路:
因为有序数组,有与目标值相等的数的时候返回该位置n,如果没有与目标值相等的数,该数应该插入到第一次比目标值大的位置,也是n。所以两个可以合并起来。最后,如果目标值比数组中所有数都大,则插入到数组最后。
solution代码:
package LeetCode.searchInsert;
/*
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。
如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 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
*/
public class searchInsertSolution {
public static int solution(int[] nums,int target){
//遍历整个数组,找到相等或者第一个大于target的位置并返回
for (int i = 0; i < nums.length; i++) {
if (nums[i] >= target){
return i;
}
}
//如果target大于数组中的所有数,则插入位置等于数组长度
return nums.length;
}
}
测试代码:
package LeetCode.searchInsert;
import java.util.Scanner;
public class searchInsertMain {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("输入数组长度:");
int n = scan.nextInt();
int nums[] = new int[n];
System.out.println("输入数组:");
for (int i = 0; i < n; i++) {
nums[i] = scan.nextInt();
}
System.out.println("输入目标值:");
int target = scan.nextInt();
System.out.println("匹配位置:" + searchInsertSolution.solution(nums,target));
}
}
测试用例:
LeetCode测试: