在原数组中通过修改来复制零。

huangapple go评论97阅读模式
英文:

Duplicate zero in array by modifying the array in place

问题

以下是您要翻译的代码部分:

public static void addPos() {
    int arr[] = { 1, 2, 0, 3, 0, 5, 0, 7, 8 };
    int result[] = new int[arr.length];
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == 0) {
            int loc = i;
            for (int j = 0; j < loc; j++) {
                result[j] = arr[j];
                result[loc] = 0;
            }
            for (int j = loc + 1; j < arr.length; j++) {
                result[j] = arr[j - 1];
            }
        }
    }
    for (int k = 0; k < arr.length; k++)
        System.out.println(result[k]);
}

希望这对您有所帮助。

英文:

> There is a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right. The elements beyond the length of the original array are not written.

We have to modify input array in place and doesn't have to create new array.

So I created that but it is duplicating the zero which is at the end of array and not the previous zeros. Can somebody help me with this?

public static void addPos() {
    int arr[] = { 1, 2, 0, 3, 0, 5, 0, 7, 8 };
    int result[] = new int[arr.length];
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == 0) {
            int loc = i;
            for (int j = 0; j < loc; j++) {
                result[j] = arr[j];
                result[loc] = 0;
            }
            for (int j = loc + 1; j < arr.length; j++) {
                result[j] = arr[j - 1];
            }
        }
    }
    for (int k = 0; k < arr.length; k++)
        System.out.println(result[k]);
}

Output

1
2
0
3
0
5
0
0
7
Expected output:
1
2
0
0
3
0
0
5
0

答案1

得分: 14

每次循环迭代都会覆盖前一次迭代的结果,因此最终结果只显示最后一次迭代的结果,这会导致最后一个0被复制。

解决这个问题的一种方法是从后向前迭代。这简化了很多事情。您可以摆脱辅助的 result 数组。基本思路是,从数组的末尾开始向后移动,每次找到0时,通过将零右侧的数组重新写入来复制它。

public static void addPos() {
    int arr[] = {1, 2, 0, 3, 0, 5, 0, 7, 8};

    for (int i = arr.length - 1; i >= 0; i--) {
        if (arr[i] == 0) {
            // 复制它!
            for (int j = arr.length - 1; j > i; j--) {
                arr[j] = arr[j-1];
            }
        }
    }

    for (int k = 0; k < arr.length; k++) {
        System.out.println(arr[k]);
    }
}
英文:

Every iteration of the loop overwrites the results from the previous iteration, so the end result only shows the results from the last iteration, which duplicates the last 0 is duplicated.

One way to solve this is by iterating backwards "right to left". It simplifies a lot of things. You can get rid of the auxiliary result array. The basic idea is, go backwards in the array, and every time you find a 0, you duplicate it by rewriting the array to the right of the zero.

public static void addPos() {
    int arr[] = {1, 2, 0, 3, 0, 5, 0, 7, 8};

    for (int i = arr.length - 1; i &gt;= 0; i--) {
        if (arr[i] == 0) {
            // duplicate it!
            for (int j = arr.length - 1; j &gt; i; j--) {
                arr[j] = arr[j-1];
            }
        }
    }

    for (int k = 0; k &lt; arr.length; k++) {
        System.out.println(arr[k]);
    }
}

答案2

得分: 2

for循环会不断覆盖结果数组中的值,因此结果仅显示最后一个重复项。您根本不应该使用结果数组。应该在原始数组中保持值的移动。

您可以参考以下代码。

for (int i = 0; i < arr.length - 1; i++) {
    if (arr[i] == 0) {
        for (int j = arr.length - 1; j > i; j--) {
            arr[j] = arr[j - 1];
        }
        i++;
    }
}
英文:

The for loop keeps overwriting the values in result array, hence the result shows only last duplication.You should not be using the result array at all.Keep shipting values in the original array itself.

You can refer to below code.

for(int i=0;i&lt;arr.length-1;i++){
  if(arr[i]==0){
    for(int j=arr.length-1;j&gt;i;j--){
    arr[j]=arr[j-1];
     }
     i++;
   }
   
}

答案3

得分: 2

这段代码的中文翻译如下:

public void duplicateZeros(int[] arr) {
    int i = 0;
    
    while (i < arr.length) {
        
        if (arr[i] == 0) {
            int j = arr.length - 1;
            while (j != i) {
                arr[j] = arr[j - 1];
                j--;
            }
            i = i + 2;
        } else {
            i = i + 1;
        }
    }
}

希望这对您有帮助!

英文:
public void duplicateZeros(int[] arr)

{
int i=0;

    while(i&lt;arr.length)
    {
        
        if(arr[i]==0)
        {
            int j=arr.length-1;
            while(j != i)
            {
                arr[j]=arr[j-1];
                j--;
            }
            i=i+2;
        }
        else
        {
            i=i+1;
        }
    }
}

答案4

得分: 1

不使用任何其他数组。

class Solution {
    public void duplicateZeros(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == 0) {
                for (int j = arr.length - 1; j > i; j--) {
                    arr[j] = arr[j - 1];
                }
                i = i + 1;
            }
        }
    }
}
英文:

Without using any other Array.

class Solution {
public void duplicateZeros(int[] arr) {
    for(int i=0;i&lt;arr.length;i++){
        if(arr[i]==0){
            
            for(int j=arr.length-1;j&gt;i;j--){
                arr[j]=arr[j-1];   
            }
            i=i+1; 
        }
         
     }
  }
}

答案5

得分: 0

以下是翻译好的部分:

所以有这个

    int[] arr = { 1, 2, 0, 3, 0, 5, 0, 7, 8 };

    public static void duplicateZeros(int[] arr) {

和应该得到的结果

    { 1, 2, 0, 3, 0, 5, 0, 7, 8 }
            v___
    { 1, 2, 0, 0, 3, 0, 5, 0, 7 }
                     v___
    { 1, 2, 0, 0, 3, 0, 0, 5, 0 }

这看起来像

    for (int i = 1; i &lt; n; ++i) {
        if (arr[i - 1] == 0) {
            在位置i插入0;
        }
    }

    在位置i插入0:
        // 首先将剩余部分右移:i .. n-2
        ...
        // 然后填入0
        arr[i] = 0;

请注意,代码部分的内容未进行翻译。

英文:

So one has this:

int[] arr = { 1, 2, 0, 3, 0, 5, 0, 7, 8 };

public static void duplicateZeros(int[] arr) {

and should get

{ 1, 2, 0, 3, 0, 5, 0, 7, 8 }
        v___
{ 1, 2, 0, 0, 3, 0, 5, 0, 7 }
                 v___
{ 1, 2, 0, 0, 3, 0, 0, 5, 0 }

This looks like:

for (int i = 1; i &lt; n; ++i) {
    if (arr[i - 1] == 0) {
        insert at i a 0;
    }
}

insert at i a 0:
    // First move the remaining to the right: i .. n-2
    ...
    // Then fill in the zero
    arr[i] = 0;

答案6

得分: 0

以下是您要翻译的Python代码部分:

# 声明我们的函数
def duplicateZeros(arr):

    # 定义增量器
    i = 0

    # 遍历所有动态元素
    while i < len(arr)-1:
        # 如果字符是零
        if arr[i]==0:
            # 从数组中删除最后一个项目
            arr.pop()
            # 在当前元素前插入一个零
            arr.insert(i+1, 0)
            # 向前移动一位
            i += 1

        # 增加到下一个字符
        i += 1

希望这对您有所帮助。如果您需要进一步的翻译,请告诉我。

英文:

Python solution for anyone interested adapted from here

the solution is non-trivial if you do not separate the action of the pointer iterating over the list and the insertions. It's very easy to write a for-loop that adds 0's ad-infinitum.

def duplicateZeros(arr):

    # define the incrementor
    i = 0

    # loop through all dynamic elements
    while i &lt; len(arr)-1:
        # if the character is a zero
        if arr[i]==0:
            # remove the last item from the array
            arr.pop()
            # insert a zero in front of current element
            arr.insert(i+1, 0)
            # move one place forward
            i += 1

        # increment to the next character
        i += 1

答案7

得分: 0

Sure, here are the translated code portions:

Solution 1: 从开始到结束循环。如果找到零,则将下一个索引的元素移动并将下一个元素设置为零,然后跳过下一个。

public static void duplicateZeros(int[] arr) {
    System.out.println("开始 duplicateZeros:" + Arrays.toString(arr));

    for (int i = 0; i < arr.length - 1; ++i) {
        if (arr[i] == 0) {
            move(arr, i);
            ++i;
        }
    }

    System.out.println("结束 duplicateZeros:" + Arrays.toString(arr) + "\n");
}

private static void move(int[] arr, int index) {
    // 从索引+1开始向右移动
    for (int i = arr.length - 1; i > index; i--) {
        arr[i] = arr[i - 1];
    }

    // 在索引处填充 0
    arr[index] = 0;
}

Solution 2: 从末尾到开始循环。如果找到零,则将下一个索引的元素移动并将当前索引设置为零。

public static void duplicateZeros(int[] arr) {
    System.out.println("开始 duplicateZeros:" + Arrays.toString(arr));

    for (int i = arr.length - 1; i >= 0; i--) {
        if (arr[i] == 0) {
            move(arr, i);
        }
    }

    System.out.println("结束 duplicateZeros:" + Arrays.toString(arr) + "\n");
}

private static void move(int[] arr, int index) {
    // 从索引+1开始向右移动
    for (int i = arr.length - 1; i > index; i--) {
        arr[i] = arr[i - 1];
    }

    // 在索引处填充 0
    arr[index] = 0;
}
英文:

Solution 1: Loop from start to end. If zero is found, move the elements from next index and fill the next as zero and skip next.

public static void duplicateZeros(int[] arr) {
	System.out.println(&quot;BEGIN duplicateZeros:&quot; + Arrays.toString(arr));

    for(int i=0; i&lt;arr.length-1; ++i) {
    	if (arr[i] == 0) {
    		move(arr, i);
    		++i;
    	}
    }
    
    System.out.println(&quot;END duplicateZeros:&quot; + Arrays.toString(arr) +&quot;\n&quot;);
}

private static void move(int[] arr, int index) {
	// move to the right from index+1
	for(int i=arr.length-1; i&gt;index; i--) {
		arr[i] = arr[i-1];
	}
	
	// fill 0 at index
	arr[index] = 0 ;
}

Solution2: Loop from end to start. If zero is found, move the elements from next index and fill the current index as zero.

public static void duplicateZeros(int[] arr) {
	System.out.println(&quot;BEGIN duplicateZeros:&quot; + Arrays.toString(arr));
	
    for(int i=arr.length-1; i&gt;=0; i--) {
    	if (arr[i] == 0) {
    		move(arr, i);
    	}
    }
    
    System.out.println(&quot;END duplicateZeros:&quot; + Arrays.toString(arr) +&quot;\n&quot;);
}

private static void move(int[] arr, int index) {
	// move to the right from index+1
	for(int i=arr.length-1; i&gt;index; i--) {
		arr[i] = arr[i-1];
	}
	
	// fill 0 at index
	arr[index] = 0 ;
}

答案8

得分: 0

class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        不要返回任何东西,而是在原地修改 arr。
        """
        if len(arr) == 0:
            return arr
        index = 0
        while index < len(arr):
            print(index, end=" ")
            if arr[index] == 0:
                arr.insert(index + 1, 0)
                arr.pop()
                index += 1
            index += 1
英文:

class Solution:
    def duplicateZeros(self, arr: List[int]) -&gt; None:
        &quot;&quot;&quot;
        Do not return anything, modify arr in-place instead.
        &quot;&quot;&quot;
        if len(arr)==0:
            return arr
        index = 0
        while index &lt; len(arr):
            print(index,end=&quot; &quot;)
            if arr[index]==0:
                arr.insert(index+1,0)
                arr.pop()
                index+=1
            index+=1

huangapple
  • 本文由 发表于 2020年8月12日 22:41:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63378939.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定