Problem
Given an array, rotate the array to the right by k steps, where k is non-negative.
ExampleExample 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]
public class Solution { /** * @param nums: an array * @param k: an integer * @return: rotate the array to the right by k steps */ public int[] rotate(int[] nums, int k) { // Write your code here k = k % nums.length; //point 1 revert(nums, 0, nums.length-k-1); //point 2 revert(nums, nums.length-k, nums.length-1); revert(nums, 0, nums.length-1); return nums; } private void revert(int[] nums, int start, int end) { while (start < end) { int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } } }
文章版權歸作者所有,未經(jīng)允許請勿轉載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/71630.html
摘要:兩種方法,轉置鏡像法和公式法。首先看轉置鏡像法原矩陣為轉置后水平鏡像翻轉后所以,基本的思路是兩次遍歷,第一次轉置,第二次水平鏡像翻轉變換列坐標。公式法是應用了一個翻轉的公式如此翻轉四次即可。二者均可,并無分別。 Problem You are given an n x n 2D matrix representing an image.Rotate the image by 90 de...
摘要:而后吾當依除取余之法,化大為小,則指針不致于越界也。后欲尋右起第結點,令快指針先行數(shù)日,及至兩指針相距為,便吟鞭東指,與慢指針策馬共進。快慢指針亦止于其所焉。舞動長劍,中宮直入,直取首級,而一掌劈空,已鴻飛冥冥。自此,一代天驕,霸業(yè)已成。 Problem Given a list, rotate the list to the right by k places, where k is...
摘要:窗口前進,刪隊首元素保證隊列降序加入當前元素下標從開始,每一次循環(huán)都將隊首元素加入結果數(shù)組 Sliding Window Maximum Problem Given an array of n integer with duplicate number, and a moving window(size k), move the window at each iteration fro...
Problem Given two sorted integer arrays A and B, merge B into A as one sorted array. Notice You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements ...
摘要:思路原數(shù)組長度為,則返回原數(shù)組長度不為,則至少有個元素。將所有不重復的數(shù)值賦給,而當和相等時,不做處理。最后返回的就是不同元素的個數(shù),也是新數(shù)組的長度。只有在時,才對賦值。注意,每次初始化的時候要分兩種情況,這就意味著從的時候開始遍歷。 Remove Duplicates from Sorted Array I Problem Given a sorted array, remove ...
閱讀 3551·2021-10-09 09:43
閱讀 6149·2021-09-07 10:15
閱讀 2746·2019-08-30 14:03
閱讀 3074·2019-08-29 11:01
閱讀 1715·2019-08-29 10:56
閱讀 1074·2019-08-28 17:52
閱讀 3502·2019-08-26 11:42
閱讀 2547·2019-08-26 10:33