lewenweijia / notes

🏊 dive dive diving
1 stars 0 forks source link

旋转数组 #4

Open lewenweijia opened 5 years ago

lewenweijia commented 5 years ago

核心思想: 改造反转数组函数, 可只定义反转范围 相关: leetcode #189 旋转数组

function rotateArray(nums, k) {
  k = k % nums.length;

  function reverse(nums, start, end) {
    for (let i = start, j = end - 1; i < end; i++, j--) {
      if (i >= j) break;

      [nums[i], nums[j]] = [nums[j], nums[i]];
    }
  }

  reverse(nums, 0, nums.length);
  reverse(nums, 0, k);
  reverse(nums, k, nums.length);
}