乱人伦 国语对白海角社区,五月激情丁香婷婷综合中文字幕,欧美伊人婷婷久久五月综合,亚洲精品无amm毛片,亚洲男人第一无码AV网站,国产日韩欧美丝袜一区二区,亚洲一区精品在线观看

LeetCode移动零-缅甸环球国际网页版

LeetCode移动零

2026-01-16 10:26:32投稿人:彩神8APP官網(wǎng)下載(陜西)有限公司圍觀5463 評(píng)論

LeetCode移動(dòng)零

給定一個(gè)數(shù)組 nums,編寫一個(gè)函數(shù)將所有 0 移動(dòng)到數(shù)組的末尾,同時(shí)保持非零元素的相對(duì)順序。

說明:

  1. 必須在原數(shù)組上操作,不能拷貝額外的數(shù)組  。
  2. 盡量減少操作次數(shù)。
void moveZeroes(int* nums, int numsSize){     int count = 0, length = numsSize-1;    while (length >= 0) {         if(nums[length] == 0) {             count++;//計(jì)數(shù)            int temp = length;            while (temp < numsSize-1) {                 nums[temp] = nums[temp+1];                temp++;            }        }            length--;    }    while (count >0) {         nums[numsSize-count] = 0;        count--;    }}

官方答案:雙指針法

思路及解法

使用雙指針  ,左指針指向當(dāng)前已經(jīng)處理好的序列的尾部 ,右指針指向待處理序列的頭部 。

右指針不斷向右移動(dòng) ,每次右指針指向非零數(shù) ,則將左右指針對(duì)應(yīng)的數(shù)交換 ,同時(shí)左指針右移。

注意到以下性質(zhì) :

左指針左邊均為非零數(shù);

右指針左邊直到左指針處均為零  。

因此每次交換,都是將左指針的零與右指針的非零數(shù)交換,且非零數(shù)的相對(duì)順序并未改變 。

void swap(int *a, int *b) {     int t = *a;    *a = *b, *b = t;}void moveZeroes(int *nums, int numsSize) {     int left = 0, right = 0;    while (right < numsSize) {         if (nums[right]) {             swap(nums + left, nums + right);            left++;        }        right++;    }}
展開閱讀全文

投稿時(shí)間 :2022-01-24  最后更新 :2022-09-09