Directory link:
Lituo Programming Problems - Summary of Solutions_Share+Records-CSDN Blog
GitHub synchronous brushing project:
https://github.com/September26/java-algorithms
Link to the original title: Likou
describe:
Given an array with subscripts starting at 0nums
, the size of the array is n
, and it consists of non-negative integers.
You need to perform n - 1
a step operation on the array, where the step i
operation ( counting from 0 ) requires the following instructions to be executed nums
on the first element:i
- If
nums[i] == nums[i + 1]
, thennums[i]
the value of , becomes the original2
multiple,nums[i + 1]
and the value of0
. Otherwise, skip this step.
After all operations are performed , 0
move all to the end of the array .
- For example, the array
[1,0,2,0,0,1]
will become after all0
shifted to the end[1,2,1,0,0,0]
.
Returns an array of results.
Note that operations should be executed sequentially , not all at once.
Example 1:
Input: nums = [1,2,2,1,1,0] Output: [1,4,2,0,0,0] Explanation: Do the following: - i = 0: nums[0] and nums[1] are not equal, skip this step. - i = 1: nums[1] and nums[2] are equal, the value of nums[1] becomes twice the original value, and the value of nums[2] becomes 0. The array becomes [1, 4 , 0,1,1,0 ]. - i = 2: nums[2] and nums[3] are not equal, so skip this step. - i = 3: nums[3] and nums[4] are equal, the value of nums[3] becomes twice the original value, and the value of nums[4] becomes 0. The array becomes [1,4,0, 2 , 0 ,0] . - i = 4: nums[4] and nums[5] are equal, the value of nums[4] becomes twice the original value, and the value of nums[5] becomes 0. The array becomes [1,4,0,2, 0 , 0 ]. After performing all operations, move all 0's to the end of the array, resulting in an array [1,4,2,0,0,0].
Example 2:
Input: nums = [0,1] Output: [1,0] Explanation: Can't do anything except move 0 to the end.
hint:
2 <= nums.length <= 2000
0 <= nums[i] <= 1000
Problem-solving ideas:
/**
* First, perform corresponding processing for the value of nums[i] == nums[i + 1].
* Then move all 0s to the end of the array, we set an index, record the current number that is not 0, and exchange positions with num[index] every time a number that is not 0 is traversed.
*/
code:
vector<int> Solution2460::applyOperations(vector<int> &nums)
{
for (int i = 0; i < nums.size() - 1; i++)
{
if (nums[i] != nums[i + 1])
{
continue;
}
nums[i] = nums[i] * 2;
nums[i + 1] = 0;
}
int index = 0;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == 0)
{
continue;
}
int local = nums[index];
nums[index] = nums[i];
nums[i] = local;
index++;
}
return nums;
};