Algorithm

This week’s LeetCode problem is 189. Rotating Arrays

Input array [1,2,3,4,5,6,7], k = 3
Output array: [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]
class Solution {
public void rotate(int[] nums, int k) {
if (nums.length <= 1) {
return ;
}
int start = nums.length - k % nums.length;
if (start == nums.length) {
return ;
}
int[] temp = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
temp[i] = nums[i];
}
for (int i = 0; i < nums.length; i++) {
nums[i] = temp[start];
start = (start + 1) % nums.length;
}
}
}
  1. the array copy is a circular assignment, after understanding the system can be called with the function.
  2. I used to find the rule from 0, and the nums[0] after the change is equal to something, but it is more complicated to express.
  1. use System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) to copy the array.
class Solution {
public void rotate(int[] nums, int k) {
int[] ans = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
ans[(i+k) % nums.length] = nums[i];
}
System.arraycopy(ans, 0, nums, 0, nums.length);
}
}
class Solution {
private void reverse(int[] nums, int start, int end) {
int temp = 0;
while (start < end) {
temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
public void rotate(int[] nums, int k) {
reverse(nums, 0, nums.length-1);
reverse(nums, 0, k % nums.length -1);
reverse(nums, k % nums.length, nums.length-1);
}
}

Review

The English article in this week’s Review is: Happy birthday, Linux: From a bedroom project to billions of devices in 30 years

Tip

Each basic type in Java has its corresponding wrapper class. For example, int and Integer. When creating Integer, there are two methods.

Share

ARTS has been offline for over a year and a half, and now I’m picking it up again. I deleted all my previous posts before updating, to forget about the past and start over. The last three months at the beginning of each month in the circle of friends to summarize their own exercise, reading and output of the previous month, to monitor themselves. When the self-exposure, they will drive themselves and will discipline themselves to reach/approach a certain goal, it’s like when no one is paying attention, a person may be more unable to discipline themselves and more likely to expose some bad aspects of themselves because no one notices anyway.

A programmer. Share knowledge of programming, operating system, Linux kernel, and reading, thinking etc. Let us maintain a beginner mend and grow together!