My first time posting an answer. Not the best one, but at least I made it!


  • 0
    S
    public class Solution {
        public int searchInsert(int[] nums, int target) {
            boolean previous = false, next = false; 
            int i = 0;
            if (target < nums[i]) return i; 
            if (nums.length == 1) return target <= nums[0]? 0:1;
            for ( i = 0; i < nums.length-1; i++) {
                if (nums[i] == target) return i; 
                if (nums[i] < target) previous = true; 
                if (nums[i+1] > target) next = true;
                if (previous && next) return (i+1); 
                previous = false; 
                next = false; 
            }
            return target == nums[i] ? i:(i+1); 
        }
    }
    

    I realized that when I began to solve the medium problems, I somehow gave up independent thinking and simply looking at previous discussion. This time, I tried to solve the problem myself, and my solution got AC.

    The code looks a bit bizarre. And of course any suggestion is welcome!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.