Skip to content

LeetCode题解:27. 移除元素,JavaScript,详细注释 #368

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
chencl1986 opened this issue Aug 19, 2021 · 0 comments
Open

LeetCode题解:27. 移除元素,JavaScript,详细注释 #368

chencl1986 opened this issue Aug 19, 2021 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:27. 移除元素

解题思路:

  1. moveIndex始终指向存放不等于val的元素位置。
  2. 遍历nums,遇到不等于val的元素,就将其存入nums[moveIndex],并将moveIndex加1。
/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function (nums, val) {
  let moveIndex = 0 // 放置不等于val的元素索引

  for (let i = 0; i < nums.length; i++) {
    // 遍历nums,将不等于val的元素放置在moveIndex位置,之后将moveIndex加1
    if (nums[i] !== val) {
      nums[moveIndex++] = nums[i]
    }
  }

  // moveIndex最终的值就是新的长度
  return moveIndex
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant