Prompt: Given a fixed length array of integers, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place, do not return anything from your function.
With this input: [8,4,5,0,0,0,0,7], the expected output: [8,4,5,0,0,0,0,0] My Solution returns: [8,8,4,5,0,0,0,0]
class Solution { public void duplicateZeros(int[] arr) { int possible_duplicates = 0; //items remaining is total spaces - duplicate zero's //first pass to determine number of zeros to duplicate int arr_length = arr.length - 1; for(int item = 0; item <= arr_length; item++) { if (arr[item] == 0) { //Edge case: no more space to duplicate zero if(item == arr.length) { //set the final index to 0 since it wont be duplicated just shifted down arr[arr_length + possible_duplicates] = 0; arr_length--; break; } possible_duplicates++; arr_length--; } } //second pass to input new array, in place //from the last element of the new array, shift towards right based on duplicate count for (int i = arr_length; i >= 0; i--){ if (arr[i] == 0){ arr[i + possible_duplicates] = 0; possible_duplicates--; arr[i + possible_duplicates] = 0; } else { arr[i + possible_duplicates] = arr[i]; } } } }
https://stackoverflow.com/questions/67442508/1089-leetcode-duplicate-zeros-where-is-the-bug May 08, 2021 at 06:50AM
没有评论:
发表评论