My Java solution


  • 0
    D
    public class Solution {
        public int searchInsert(int[] A, int target) {
            //error check
            if(A == null) {
                return 0;
            }
            //special cases
            if(target < A[0]) {
                return 0;
            }
            if(target > A[A.length - 1]) {
                return A.length;
            }
            //perform binary search
            int left = 0;
            int right = A.length - 1;
            while(left <= right) {
                int mid = (right - left) / 2 + left;
                if(A[mid] == target) {
                    return mid;
                }
                else if(target < A[mid]) {
                    right = mid - 1;
                }
                else {
                    left = mid + 1;
                }
            }
            return left;
        }
    }
    

    I just switched from C++ to Java. Hope you guys could provide some suggestions for me.

    Thanks.


  • 0
    Y
    class Solution {
    public:
        int searchInsert(int A[], int n, int target) {
            int s = 0;
            int e = n-1;
            int mid;
            while(s<=e) {
                mid = (s+e)/2;
                if(A[mid] == target)
                    return mid;
                else if(A[mid] > target)
                    e = mid-1;
                else
                    s = mid+1;
            }
            return s;
        }
    };

  • 0

    your answer is too complicated, you can try to optimize it.


Log in to reply
 

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