A solution without binary search


  • 0
    L

    I've got a solution with unstable time complexity while the worst is O(N)

    Is it feasible?

        public int search(int[] nums, int target) {
            if (nums == null || nums.length == 0) {
                return -1;
            }
            if (target > nums[0]) {
                // find ahead
                for (int i = 1; i < nums.length; i++) {
                    if (target == nums[i]) {
                        return i;
                    }
                    if (nums[i] <= nums[i - 1]) {
                        break;
                    }
                }
            } else if (target < nums[0]) {
                // find behind
                for (int i = nums.length - 1; i > 0; i--) {
                    if (target == nums[i]) {
                        return i;
                    }
                    if (nums[i] <= nums[i - 1]) {
                        break;
                    }
                }
            } else {
                return 0;
            }
            return -1;
        }
    

Log in to reply
 

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