LeetCode:旋转数组(c#)
程序员文章站
2022-04-28 09:55:48
...
题目内容
c#代码实现
实现方法1
public class Solution {
public void Rotate(int[] nums, int k) {
k %= nums.Length;
if (k < 1) return;
for (int i = 0; i < k; i++)
{
var temp = nums[nums.Length - 1];
Array.Copy(nums, 0, nums, 1, nums.Length - 1);
nums[0] = temp;
}
}
}
实现方法2
public class Solution {
public void Rotate(int[] nums, int k) {
k %= nums.Length;
if (k < 1) return;
Reversal(nums, 0, nums.Length - 1);
Reversal(nums, 0, k - 1);
Reversal(nums, k, nums.Length - 1);
}
private void Reversal(int[] nums, int start, int end)
{
while (start < end)
{
var temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
}
上一篇: C# 获取用户IP地址(转载)
下一篇: Python之禅&编码规范&一键排版