国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Leetcode: Rotate Array

2019-11-14 23:06:24
字體:
來源:轉載
供稿:網友
Leetcode: Rotate Array
Rotate an array of n elements to the right by k steps.For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].Note:Try to come up as many solutions as you can, there are at least 3 different ways to solve this PRoblem.[show hint]Hint:Could you do it in-place with O(1) extra space?

Naive想法就是保存一個原數組的拷貝,然后把原數組分成前len-k個元素和后k個元素兩部分,把后k個元素放到前len-k個元素前面去。這樣做需要O(N)空間

in-place做法是:

(1) reverse the array;

(2) reverse the first k elements;

(3) reverse the last n-k elements.

The first step moves the first n-k elements to the end, and moves the last k elements to the front. The next two steps put elements in the right order.

 1 public class Solution { 2     public void rotate(int[] nums, int k) { 3         int len = nums.length; 4         k %= len; 5         reverse(nums, 0, len-1); 6         reverse(nums, 0, k-1); 7         reverse(nums, k, len-1); 8     } 9     10     public void reverse(int[] nums, int l, int r) {11         while (l <= r) {12             int temp = nums[l];13             nums[l] = nums[r];14             nums[r] = temp;15             l++;16             r--;17         }18     }19 }

需要注意的是第4行,右移偏移量k可能比數組長度len要大,所以要先 k%=len;


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 二连浩特市| 石泉县| 甘南县| 开远市| 公主岭市| 桑植县| 南宁市| 枝江市| 阳山县| 老河口市| 淮安市| 台湾省| 秦安县| 报价| 阿克陶县| 买车| 吉林省| 琼海市| 彩票| 巨野县| 双桥区| 鞍山市| 金湖县| 东乡族自治县| 丹江口市| 宜昌市| 禹城市| 宁陕县| 嘉禾县| 文水县| 龙里县| 年辖:市辖区| 南投市| 郯城县| 尉犁县| 南靖县| 平舆县| 沾化县| 东乌珠穆沁旗| 武汉市| 运城市|