var searchRange = function(nums, target) {
let l = -1
let r = nums.length
let mid
while(l+1 != r){
mid = Math.floor((l+r)/2)
if(nums[mid] < target){
l = mid
}else{
r = mid
}
}
if(nums[r] != target) return [-1,-1]
let ans = [r]
while(nums[r] == target){
r ++
}
ans.push(r-1)
return ans
};
var searchInsert = function(nums, target) {
let l =-1
let r =nums.length
while(l+1 != r){
let mid = Math.floor((l+r)/2)
if(nums[mid]==target) return mid
else if(nums[mid] < target){
l=mid
}else{
r=mid
}
}
return r
};
var mySqrt = function(x) {
let l = 0
let r = x + 1
let mid
while(l+1 !=r){
mid = Math.floor((l+r)/2)
if(mid*mid > x){
r = mid
}else{
l= mid
}
}
return l
};
var isPerfectSquare = function(num) {
let l = 0
let r = num + 1
let mid
while(l+1 !=r){
mid = Math.floor((l+r)/2)
if(mid*mid > num){
r = mid
}else{
l= mid
}
}
if(l*l < num) return false
return true
};
var removeDuplicates = function(nums) {
if(nums.length < 2) return nums
let i = 1
let target = nums[0]
for(let j = 1; j < nums.length; j ++){
if(nums[j] != target){
nums[i++] = nums[j]
target = nums[j]
}
}
return i
};
var moveZeroes = function(nums) {
let i = 0
let cnt = 0
for(let j = 0; j < nums.length; j ++){
if(nums[j] != 0){
nums[i++] = nums[j]
}else cnt ++
}
while(cnt){
nums[nums.length-cnt] = 0
cnt --
}
};
- 先使用栈来处理一下回退符
'#' - 然后直接比较就可以了
var backspaceCompare = function(s, t) {
let arrs = []
let arrt = []
for(let i = 0; i < s.length; i++){
if(s[i] === '#'){
if(arrs.length !== 0){
arrs.pop()
}
}else{
arrs.push(s[i])
}
}
for(let j = 0; j < t.length; j++){
if(t[j] === '#'){
if(arrt.length !== 0){
arrt.pop()
}
}else{
arrt.push(t[j])
}
}
if(arrt.length !== arrs.length) return false
let index1 = 0
let index2 = 0
while(index1 < arrs.length && index2 < arrt.length){
if(arrs[index1 ++] !== arrt[index2 ++]) return false
}
return true
};
var spiralOrder = function(matrix) {
let arr = []
let m = matrix.length
let n = matrix[0].length
for(let i = 0; i < m; i++){
arr.push((new Array(n)).fill(0))
}
let k = 1
let next = [[0,1],[1,0],[0,-1],[-1,0]]
let x = 0
let y = 0
let nx = 0
let ny = 0
let ans = []
let flag = 0
while(k <= m*n){
x = nx
y = ny
arr[x][y] = 1
ans.push(matrix[x][y])
nx = x + next[flag][0]
ny = y + next[flag][1]
if(nx < 0 || nx >= m || ny < 0 || ny >= n || arr[nx][ny] == 1){
flag = (flag + 1) % 4
nx = x + next[flag][0]
ny = y + next[flag][1]
}
k++
}
return ans
};
|