[英]rotate the elements of the given array k times to the right
在i=0
時,您試圖訪問nums[i-1]
= num[-1]
這是一個無效位置,因此會引發ArrayOutOfBound
異常。
因此,修改后的版本將是:
for (j=0; j<k; j++)
{
for (int i=1;i<nums.length;i++)
{
temp=nums[i-1];
nums[i-1]=nums[i];
nums[i]=temp;
}
}
但是當您將元素向左移動時,上述內容會將數組left
而不是向右旋轉k
次。 因此,要獲得right
的旋轉,您需要從數組末尾移動元素。 喜歡:
for (j=0; j<k; j++)
{
for (int i=nums.length-1; 0<i; i--)
{
// shifting towards the right
temp=nums[i-1];
nums[i-1]=nums[i];
nums[i]=temp;
}
}
編輯(來自上面的評論) :如果i為 0,則您試圖獲得 -1 的索引,這將引發 ArrayOutOfBounds 異常。 如果i從 1 開始,那么您不會處理第一個數字。
這是可用於向右旋轉整數的函數:
public void rotate(int[] nums, int k) {
int arrLen = nums.length;
// If the number of times you want to rotate is bigger than the size of the array, get the minimum number of rotations to get the same result.
while (k > n) {
k = k - arrLen;
}
k = arrLen - k;
k = k % arrLen;
int i, m, n, temp;
int g_c_d = gcd(k, arrLen);
// Move the value in the i-th index
for (i = 0; i < g_c_d; i++) {
temp = arr[i];
m = i;
while (true) {
n = m + k;
if (n >= arrLen) {
n = n - arrLen;
}
if (n == i) {
break;
}
arr[m] = arr[n];
m = n;
}
arr[m] = temp;
}
}
// Find the greatest common divisor of two numbers, a and b
public void gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
讓我簡要解釋一下它的作用。 這是最知名的算法之一:雜耍。 您將數組分成n個集合,其中n表示數組長度的最大公約數和要旋轉的次數。 然后,您在集合內移動數字。
就時間而言,這可能是最有效的(因為它的時間復雜度是O(n) )。
更好的解決方案是使用值“0”獲取給定數組的副本,然后遍歷給定數組以獲得 new_index。
順時針旋轉數組的 New_index 公式:
for(int i=0;i<nums.length;i++){
int new_index = (old_index+k)%(a.length)
copy[new_index] = a[old_index]
}
Now the entire function code would be:
public static void rotate(int[] a, int k)
{
int n = a.length;
int[] copy = new int[n];
// fill the values with zeroes
for(int i=0;i<n;i++){
copy[i]=0;
}
// rotate the array
for(int i=0;i<n;i++){
int new_index = (i+k)%n;
copy[new_index] = a[i];
}
// Now that the array is copied, copy the elements to the original array. Because they asked to rotate the given array.
for(int i=0;i<n;i++){
a[i]=copy[i];
}
}
function solution(arr, k) {
if(k == 0) return arr;
if(arr.length == k) return arr;
if(arr !== undefined && arr !== null){
let counter = k > arr.length ? k % arr.length : k;
let rotArray = [];
rotArray = arr.slice(arr.length - counter, arr.length).concat(arr.slice(0,arr.length - counter))
return rotArray;
}
return arr;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.