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--; } } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/71630.html
摘要:兩種方法,轉(zhuǎn)置鏡像法和公式法。首先看轉(zhuǎn)置鏡像法原矩陣為轉(zhuǎn)置后水平鏡像翻轉(zhuǎn)后所以,基本的思路是兩次遍歷,第一次轉(zhuǎn)置,第二次水平鏡像翻轉(zhuǎn)變換列坐標(biāo)。公式法是應(yīng)用了一個(gè)翻轉(zhuǎn)的公式如此翻轉(zhuǎn)四次即可。二者均可,并無分別。 Problem You are given an n x n 2D matrix representing an image.Rotate the image by 90 de...
摘要:而后吾當(dāng)依除取余之法,化大為小,則指針不致于越界也。后欲尋右起第結(jié)點(diǎn),令快指針先行數(shù)日,及至兩指針相距為,便吟鞭東指,與慢指針策馬共進(jìn)??炻羔樢嘀褂谄渌?。舞動長劍,中宮直入,直取首級,而一掌劈空,已鴻飛冥冥。自此,一代天驕,霸業(yè)已成。 Problem Given a list, rotate the list to the right by k places, where k is...
摘要:窗口前進(jìn),刪隊(duì)首元素保證隊(duì)列降序加入當(dāng)前元素下標(biāo)從開始,每一次循環(huán)都將隊(duì)首元素加入結(jié)果數(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ù)組長度不為,則至少有個(gè)元素。將所有不重復(fù)的數(shù)值賦給,而當(dāng)和相等時(shí),不做處理。最后返回的就是不同元素的個(gè)數(shù),也是新數(shù)組的長度。只有在時(shí),才對賦值。注意,每次初始化的時(shí)候要分兩種情況,這就意味著從的時(shí)候開始遍歷。 Remove Duplicates from Sorted Array I Problem Given a sorted array, remove ...
閱讀 3559·2021-10-09 09:43
閱讀 6172·2021-09-07 10:15
閱讀 2757·2019-08-30 14:03
閱讀 3087·2019-08-29 11:01
閱讀 1724·2019-08-29 10:56
閱讀 1087·2019-08-28 17:52
閱讀 3508·2019-08-26 11:42
閱讀 2563·2019-08-26 10:33