Binary search in JAVA


  • 1
    L
    public class Solution {
        public List<String> summaryRanges(int[] nums) {
    	List<String> li = new LinkedList<>();
    	int i = 0;
    	while (i < nums.length) {
    	    int k = getN(nums, i);
    	    if (i != k) li.add("" + nums[i] + "->" + nums[k]);
    	    else li.add("" + nums[i]);
    	    i = k + 1;
    	}
    	return li;
        }
        private int getN(int[] nums, int k) {
    	int l = k, r = nums.length;
    	while (l + 1 < r) {
    	    int m = (l + r) / 2;
    	    if (nums[m] - nums[l] == m - l) l = m;
    	    else r = m;
    	}
    	return l;
        }
    }

  • 0
    F

    Should this solution be O(nlogn)?


Log in to reply
 

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