[ 问题: ]

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.

翻译:给你一个排好序的数组和一个目标值,请找出目标值能够插入数组的位置。


[ 分析: ]
Here are few examples.

[1,3,5,6], 5 → 2

[1,3,5,6], 2 → 1

[1,3,5,6], 7 → 4

[1,3,5,6], 0 → 0
注意:一定要考虑一些特殊情况,如数组为null等。


[ 解法: ]
①. 常规解法:从数组索引为0的位置開始找,时间复杂度为O(n),accepted
public class Solution {
public int searchInsert(int[] A, int target) {
if (A != null) {
for (int i = 0; i < A.length; i++) {
if (target == A[i] || target < A[i]) {
return i;
}
}
return A.length;
}
return -1;
} public static void main(String[] args) {
int[] arr = { 1, 3, 5, 6 };
System.out.println(new Solution().searchInsert(arr, 5)); // 5 -> 2
System.out.println(new Solution().searchInsert(arr, 2)); // 2 -> 1
System.out.println(new Solution().searchInsert(arr, 7)); // 7 -> 4
System.out.println(new Solution().searchInsert(arr, 0)); // 0 -> 0
}
}

②. 二分查找:时间复杂度log2n

前提条件:一定是有序数组。

public class Solution {
public int searchInsert(int[] A, int target) {
int mid;
int low = 0;
int high = A.length - 1;
while (low < high) {
mid = (low + high) / 2;
if (A[mid] < target) {
low = mid + 1;
} else if (A[mid] > target) {
high = mid - 1;
} else {
return mid;
}
} return target > A[low] ? low + 1 : low;
} public static void main(String[] args) {
int[] arr = { 1, 3, 5, 6 };
System.out.println(new Solution().searchInsert(arr, 5)); // 5 -> 2
System.out.println(new Solution().searchInsert(arr, 2)); // 2 -> 1
System.out.println(new Solution().searchInsert(arr, 7)); // 7 -> 4
System.out.println(new Solution().searchInsert(arr, 0)); // 0 -> 0
}
}

最新文章

  1. 浅淡HTML5移动Web开发
  2. apt-get报错could not get lock /var/lib/dpkg/lock -open等
  3. cookie 暂时保存内容与恢复
  4. Map-API及详解
  5. hive操作语句使用详解
  6. 【风马一族_Android】 图能
  7. DevExpress控件汉化类 z
  8. 14-利用SVD简化数据
  9. 三、IF...ELSE和缩进
  10. vivado License导入方法与资源获取
  11. 安卓开发笔记(二十一):Android Studio如何创建assets目录
  12. .NET Core: 在.NET Core中进行单元测试
  13. 关于四种语言中substring()方法参数值的解析
  14. C#异步编程のParallel(并行)
  15. 4-23 模块 hashlib ,configparser,loging,collections
  16. (转)request模拟知乎登录(无验证码机制
  17. Codeforces Round #Pi (Div. 2)(A,B,C,D)
  18. Linux /python --- zipinfo命令
  19. Codeforces 989A:A Blend of Springtime
  20. 第130天:移动端-rem布局

热门文章

  1. 【构造】【分类讨论】Codeforces Round #435 (Div. 2) C. Mahmoud and Ehab and the xor
  2. 【Splay】【启发式合并】hdu6133 Army Formations
  3. BUG:upstream timed out (10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected
  4. kosaraju算法求强连通分量
  5. #Html学习积累#分割线中间添加文字
  6. .net中的泛型
  7. SQL 的四种分类 DDL,DML,DCL,TCL
  8. 万里长征第二步——django个人博客(第四步 ——创建数据库)
  9. 如何在sublime3项目设置中设置python模块的搜索路径?ImportError: No module named *的解决办法
  10. [转]SSIS高级转换任务—在Package中是用临时表是需要设置RetainSameConnection属性