LeetCode刷题记录(1)

前端开发 作者: 2024-08-22 23:00:01
使用语言: JavaScript。 从简单题开始写的,只放上了代码,没有写思路。

使用语言: JavaScript。

两数之和

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums,target) {
  let temp = [];
  for (let i = 0; i < nums.length; i++){
    let diff = target - nums[i];
    
    if (temp[diff] !== undefined) {
      return [temp[diff],i];
    }

    temp[nums[i]] = i;
  }
};
var twoSum = function(nums,target) {
  let map = new Map();
  for (let i = 0; i < nums.length; i++) {
    let dif = target-nums[i]
    if (map.has(dif)) {
      return [map.get(dif),i]
    }
    map.set(nums[i],i);
  }
};

整数反转

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {
  const res = parseInt(x.toString().split('').reverse().join(''));

  if (res < -2147483648 || res > 2147483647) {
    return 0
  }

  return x > 0 ? res : -res;
};

回文数

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
  const reX = x.toString().split('').reverse().join('');

  if (x.toString() !== reX) {
    return false;
  }
  return true;
};
var isPalindrome = function(x) {
  if (x < 0 || (x % 10 === 0 && x !== 0)) {
    return false;
  }

  let reNum = 0;
  while(x > reNum) {
    reNum = reNum * 10 + x % 10;
    x = parseInt(x / 10);
  }

  return reNum === x || parseInt(reNum / 10) === x;
};

罗马数字转整数

/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
  // IV 4 IX 9 XL 40 XC 90 CD 400 CM 900
  let dir = {
    I: 1,V: 5,X: 10,L: 50,C: 100,D: 500,M: 1000
  };

  let res = 0;
  for (let i = 0; i < s.length; i++) {
    const current = dir[s[i]];
    const next = dir[s[i+1]];

    if (next / current === 5 || next / current === 10) {
      res += next - current;
      i++;
    } else {
      res += current;
    }
  }
  return res;
};

最长公共前缀

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
  if (strs.length === 1) {
    return strs[0];
  }

  strs.sort((current,next) => current.length - next.length);

  let publicStr = '';
  for (let i = 0; i < strs.length - 1; i++) {
    let current = publicStr ? publicStr : strs[i];
    let next = strs[i + 1];
    let currentLength = current.length;

    if (current === '') {
      return '';
    }

    while (next.indexOf(current) !== 0) {
      currentLength--;
      current = current.substr(0,currentLength);

      if (current === '') {
        return '';
      }
    }

    publicStr = current;
  }

  return publicStr;
};

有效的括号

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
  while (s.includes('()') || s.includes('[]') || s.includes('{}')) {
    s = s.replace('{}','');
    s = s.replace('[]','');
    s = s.replace('()','');
  }
  return s === '';
};
var isValid = function(s) {
  const map = {
    '(':')','[':']','{':'}'
  };

  let leftArr = [];
  for (let ch of s) {
    if (ch in map) {
      leftArr.push(ch);
    } else {
      if (ch !== map[leftArr.pop()]) {
        return false;
      }
    }
  }

  return !leftArr.length;
};

合并两个有序链表

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function(l1,l2) {
  if (l1 === null) {
    return l2;
  }
  if (l2 === null) {
    return l1;
  }

  if (l1.val < l2.val) {
    l1.next = mergeTwoLists(l1.next,l2);
    return l1;
  } else {
    l2.next = mergeTwoLists(l1,l2.next);
    return l2;
  }
};

删除排序数组中的重复项

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function (nums) {
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] === nums[i + 1]) {
      nums.splice(i,1);
      i--;
    }
  }
  return nums.length;
};
var removeDuplicates = function (nums) {
  var len = 1;
  for (var i = 1; i < nums.length; i++) {
    if (nums[i] !== nums[i - 1]) {
      nums[len++] = nums[i];
    }
    console.log(nums)
  }
  return len;
};

移除元素

/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function(nums,val) {
  let len = 0;
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] !== val) {
      nums[len++] = nums[i];
    }
  }
  return len;
};

搜索插入位置(二分法)

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var searchInsert = function (nums,target) {
  nums.push(target);
  return nums.sort((a,b) => a - b).indexOf(target);
};
var searchInsert = function (nums,target) {
  var left = 0;
  var right = nums.length - 1;

  if (target > nums[right]) {
    return right + 1;
  }

  while (left < right) {
    var index = parseInt((left + right) >>> 1); //取左中位数

    if (nums[index] < target) {
      left = index + 1;
      //中位数小于目标值,削去区间左侧
    } else {
      right = index;
      //中位数大于等于目标值,削去区间右侧
    }
  }
  return left;
};

最大子序和

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxSubArray = function(nums) {
  let ans = nums[0];
  let sum = 0;

  for (const num of nums) {
    if (sum > 0) {
      sum += num;
    } else {
      sum = num;
    }
    ans = Math.max(ans,sum);
  }

  return ans;
};

最后一个单词的长度

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
  const arr = s.trim().split(' ');

  return arr[arr.length - 1].length;
};
var lengthOfLastWord = function (s) {
  let end = s.length - 1;
  while (end >= 0 && s[end] == ' ') {
    end--;
  }
  if (end < 0) {
    return 0;
  }
  let start = end;
  while (start >= 0 && s[start] != ' ') {
    start--;
  }
  return end - start;
};

加一

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
  for (let i = digits.length - 1; i >= 0; i--) {
    digits[i]++;   
    if (digits[i] === 10) {
      digits[i] = 0;
      if (i === 0) {
        return [1,...digits];
      }
    } else {
      break;
    }
  }
  return digits;
};
var plusOne = function(digits) {
    const len = digits.length;
    for(let i = len - 1; i >= 0; i--) {
        digits[i]++;
        digits[i] %= 10;
        if(digits[i]!=0)
            return digits;
    }
    
    return [1,...digits];
};

二进制求和

/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function (a,b) {
  const diff = a.length - b.length;

  if (diff < 0) {
    for (let i = 0; i < -diff; i++) {
      a = '0' + a;
    }
  }
  if (diff > 0) {
    for (let i = 0; i < diff; i++) {
      b = '0' + b;
    }
  }

  let arrA = a.split('');
  let arrB = b.split('');

  const len = a.length;
  let carry = 0;
  for (let i = len - 1; i >= 0; i--) {
    const num = parseInt(arrA[i]) + parseInt(arrB[i]) + carry;

    carry = num === 1 || num === 0 ? 0 : 1;

    if (num !== 0) {
      arrA[i] = num % 2 === 0 ? '0' : '1';
    }
  }

  if (carry === 1) {
    return ['1',...arrA].join('');
  }
  return arrA.join('');
};
var addBinary = function(a,b) {
    let ans = "";
    let ca = 0;
    for(let i = a.length - 1,j = b.length - 1;i >= 0 || j >= 0; i--,j--) {
        let sum = ca;
        sum += i >= 0 ? parseInt(a[i]) : 0;
        sum += j >= 0 ? parseInt(b[j]) : 0;
        ans += sum % 2;
        ca = Math.floor(sum / 2);
    }
    ans += ca == 1 ? ca : "";
    return ans.split('').reverse().join('');
};

x 的平方根(二分法)

/**
 * @param {number} x
 * @return {number}
 */
var mySqrt = function (x) {
  if (x == 0 || x == 1) {
    return x;
  }

  var left = 1;
  var right = x;
  while (left <= right) {
    var middle = left + ((right - left) >>> 1);
    
    if (middle * middle === x) {
      return middle;
    } else if (middle * middle > x) {
      right = middle - 1;
    } else {
      left = middle + 1;
    }
  }
  return right;
};
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_66918.html
LeetCode刷题记录(1)