搜索插入位置

介绍:搜索插入位置,如果有就返回索引,如果没有就返回他应该插入那个索引位置

package cut;

public class SearchInsert {
    public static void main(String[] args) {
        int[] ints = {1, 3, 5, 6};
        Solution4 solution4 = new Solution4();
        solution4.searchInsert(ints, 7);
    }
}


上面是测试:
//-----------------
下面是封装好的代码:


/**
 * 示例 1:
 *
 * 输入: nums = [1,3,5,6], target = 5
 * 输出: 2
 * 示例 2:
 *
 * 输入: nums = [1,3,5,6], target = 2
 * 输出: 1
 * 示例 3:
 *
 * 输入: nums = [1,3,5,6], target = 7
 * 输出: 4
 *

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


        int length = nums.length;
        System.out.println(length);
        int total = 0;
        boolean goal = true;
        while (goal) {
            if (nums[total] < target) {
                total++;
            }
             /*
             1-下面这个 :if (total >= length) 的解析
             2-利用"索引"比"长度"少1的做法,当索引到达长度的位置,也就是超出数组的最后一个数的位置,就在着时候把内容加入,并且直接得到这个地方的索引,就是长度。
             3-总结:当遇到[1, 3, 5, 6]和7比,如果7不在这些范围里面,就一个个对比。放在该放的位置。
             我们可以看出,7比这些都大,他将会到 索引为4的这个地方,开始索引为4,数组索引一共才3。
             4-发现:当都比这些都大的时候,这个数的索引 = 数组索引+1 ,可是--> 数组索引+1 = 不就是长度吗
             所以,我们当索引 = 长度的时候,就说明这个索引到达末位+1
             返回回来,就是7应该在的位置。
              */
            if (total >= length) {
                goal = false;
                return total;
                // System.out.println(total);
            }
            if (nums[total] > target) {
                goal = false;
                return total;
            }
        }
        return -1;
    }
}

posted on 2022-07-21 16:22  陈嘻嘻-  阅读(62)  评论(0编辑  收藏  举报

导航