Leetcode 練習:2021-12-15

December 15, 2021

Maximum Subarray

題號:53

var maxSubArray = function (nums) {
  //使用 Kadane 演算法。
  let max = nums[nums.length - 1]
  let tempMax = nums[nums.length - 1]
  let i = nums.length - 2
  while(i>=0) {
    tempMax = Math.max(tempMax + nums[i], nums[i])
    max = Math.max(tempMax, max)
    i--
  }
  return max
}

Length of Last Word

題號:58

var lengthOfLastWord = function(s) {
  return s.trim().split(' ').pop().length
}

Insertion Sort List

題號:147

//不是標準的寫法。 
var insertionSortList = function(head) {
  let arr = []
  while(head) {
    arr.push(head.val)
    head = head.next
  }
  return arr
    .sort((a,b)=>a-b)
    .reduceRight((next,val)=>({next,val}), null)
}

Profile picture

Written by Wei Hung who is thinking. You should follow them on Twitter