JadeCode

[Leetcode] Algorithm Day2 Two Pointers 본문

카테고리 없음

[Leetcode] Algorithm Day2 Two Pointers

z-zero 2023. 3. 18. 20:00

977. Squares of a Sorted Array

정렬하기. 하지만 sort내장함수 쓰지 않고 시간복잡도 O(n)으로 만들기

 

1. 일단 각 숫자들을 문제에 나와있는대로 제곱을 한다.

2. 선택 정렬 알고리즘 사용한다.

* 선택정렬 알고리즘

배열을 돌면서 최소값을 찾아간다. 현재 index와 최소값을 가진 index를 swap한다.

 

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortedSquares = function (nums) {
  nums = nums.map((el) => Math.abs(el) * Math.abs(el));

  const swap = (a, b, nums) => {
    [nums[a], nums[b]] = [nums[b], nums[a]];
    return a, b;
  };

  for (let i = 0; i < nums.length; i++) {
    min_index = i;
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[min_index] > nums[j]) {
        min_index = j;
      }
    }
    swap(i, min_index, nums);
  }
  return nums;
};

https://leetcode.com/problems/squares-of-a-sorted-array/?envType=study-plan&id=algorithm-i 

 

Squares of a Sorted Array - LeetCode

Can you solve this real interview question? Squares of a Sorted Array - Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.   Example 1: Input: nums = [-4,-1,0,3,10] Out

leetcode.com

 

189. Rotate Array

k번만큼 로테이트 시켜 배열을 만든다.

일단 k가 nums의 길이보다 크면 나머지값으로 구한다.

뒤에서부터 k만큼 자른 후 앞에 shift한다.

 

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var rotate = function (nums, k) {
  k = k > nums.length ? k % nums.length : k;
  const splice = nums.splice(nums.length - k, nums.length);
  nums.unshift(...splice);
  return nums;
};

https://leetcode.com/problems/rotate-array/?envType=study-plan&id=algorithm-i 

 

Rotate Array - LeetCode

Can you solve this real interview question? Rotate Array - Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.   Example 1: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 step

leetcode.com

 

Comments