Skip to content

Instantly share code, notes, and snippets.

@hoanbka
Created November 7, 2017 17:27
Show Gist options
  • Save hoanbka/21012e52b205b9d5473a35d037a96c14 to your computer and use it in GitHub Desktop.
Save hoanbka/21012e52b205b9d5473a35d037a96c14 to your computer and use it in GitHub Desktop.
Search for a range in an ascending order array
/**
* Created by Hoan Nguyen on 11/8/2017.
* https://leetcode.com/problems/search-for-a-range/description/
*/
var searchRange = function(nums, target) {
var found = false;
var res = [];
for (var i = 0; i < nums.length; i++) {
if (nums[i] == target) {
if (!found) {
res.push(i);
found = true;
}
else {
if (nums[i] !== nums[i + 1]) res.push(i);
}
}
}
return found ? res.length === 2 ? res : [res[0], res[0]] : [-1, -1];
};
//TEST
var nums = [5, 7, 7, 8, 8, 10];
var target = 8;
console.log(searchRange(nums, target));
console.log(searchRange([1], 1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment