Java实现LeetCode_0035_SearchInsertPosition
2023-09-14 08:58:08 时间
package javaLeetCode.primary;
public class SearchInsertPosition_35 {
public static void main(String[] args) {
int []nums = {1,3,5,6};
System.out.println(searchInsert_2(nums, 0));
}//end main()
/**
* Conventional idea.
* sequential search.
* */
/*
* Test Data:
* Input: [1,3,5,6], 5
* Output: 2
*
*Input: [1,3,5,6], 2
* Output: 1
*
*Input: [1,3,5,6], 7
* Output: 4
*
*Input: [1,3,5,6], 0
* Output: 0
* */
public static int searchInsert_1(int[] nums, int target) {
for(int i =0;i<nums.length;i++) {
if(nums[i]==target) {
return i;
}else {
continue;
}//end if
}//end for
for(int i=0;i<nums.length;i++) {
if(target>nums[i]) {
continue;
}else {
return i;
}//end if
}//end for
return nums.length;
}//end searchInsert()
/**
* Conventional idea.
* binary search.
* */
public static int searchInsert_2(int[] nums, int target) {
int low = 0;
int high = nums.length-1;
int mid = -1;
int returnInt = -1;
//Search the array "nums" for the "target" target.
while(low<=high) {
mid = (low+high)/2;
if(target==nums[mid]) {
returnInt = mid;
return returnInt;
}else if(target<nums[mid]) {
high = mid - 1;
}else if(target>nums[mid]) {
low = mid +1;
}//end if
}//end while
//Find insert position.
if(low>high) {
for(int i=0;i<nums.length;i++) {
if(target>nums[i]) {
continue;
}else {
returnInt = i;
return returnInt;
}//end if
}//end for
}//end if
return nums.length;
}//end searchInsert()
}//end SearchInsertPosition_35
相关文章
- Java实现 LeetCode 836 矩形重叠(暴力)
- Java实现 LeetCode 793 阶乘函数后K个零 (分析)
- Java实现 LeetCode 783 二叉搜索树节点最小距离(遍历)
- Java实现 LeetCode 773 滑动谜题(BFS)
- Java实现 LeetCode 765 情侣牵手(并查集 || 暴力)
- Java实现 LeetCode 747 至少是其他数字两倍的最大数(暴力)
- Java实现 LeetCode 705 设计哈希集合(使用数组保存有没有被用过)
- Java实现 LeetCode 704 二分查找(二分法)
- Java实现 LeetCode 704 二分查找(二分法)
- Java实现 LeetCode 688 “马”在棋盘上的概率(DFS+记忆化搜索)
- Java实现 LeetCode 491递增子序列
- Java实现 LeetCode 478 在圆内随机生成点
- Java实现 LeetCode 470 用 Rand7() 实现 Rand10()
- Java实现 LeetCode 457 环形数组循环
- Java实现 LeetCode 430 扁平化多级双向链表
- Java实现 LeetCode 413 等差数列划分
- Java实现 LeetCode 410 分割数组的最大值
- Java实现 LeetCode 385 迷你语法分析器
- Java实现 LeetCode 350 两个数组的交集 II(二)
- Java实现 LeetCode 290 单词规律
- Java实现 LeetCode 162 寻找峰值
- Java实现 LeetCode 133 克隆图
- Java实现 LeetCode 82 删除排序链表中的重复元素 II(二)
- Java实现 LeetCode 50 Pow(x,n)
- Java实现 LeetCode 41 缺失的第一个正数
- Java实现 LeetCode 4 寻找两个有序数组的中位数
- Java实现 LeetCode 240 搜索二维矩阵 II
- 详解jvm之java类加载机制和类加载器(ClassLoader) 深入理解Java类加载器(ClassLoader) 如何自定义类加载器 深入说明双亲委派 双亲委派模型的破坏者-线程上下文类加载器