給一個陣列,讓裡面的元素往右旋轉 k 次。
LeetCode 題目連結
https://leetcode.com/problems/rotate-array/
題目
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7]
and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99]
and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input:[1,2,3,4,5,6,7]
and k = 3 Output:[5,6,7,1,2,3,4]
Explanation: rotate 1 steps to the right:[7,1,2,3,4,5,6]
rotate 2 steps to the right:[6,7,1,2,3,4,5]
rotate 3 steps to the right:[5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99]
and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
Accept 作法
總之不給另外一個新的陣列,需要在 nums 一次完整 (空間複雜度O(1))。我的作法是陣列其他元素不斷與 index = 0 的位置交換。
Runtime: 304 ms
Memory: 42.1 MB
Java
Runtime: 304 ms
Memory: 42.1 MB
class Solution { public void rotate(int[] nums, int k) { for(int i = 0;i < k; i++){ for(int j = 0; j <nums.length;j++){ if(j+1 <nums.length){ int temp = nums[j+1]; nums[j+1] = nums[0]; nums[0] = temp; } } } } }
更多 LeetCode 相關資源
複習程式面試書籍
除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。
沒有留言:
張貼留言