To delete an array element 0

Subject description:

Given a one-dimensional array, in which the element 0 is deleted, the relative positions of nonzero elements remains unchanged, the ultimate goal of the array remain in the original array, and the array of elements other than certain lengths are all set to zero.

 

Problem-solving ideas:

(1) nonzero elements of the array moves forward, the time complexity of O (n).

Ideas: first non-zero elements forward by the last remaining position and then reset to 0.

 1 public void moveZeroes(int[] nums) {
 2         if(nums.length < 1)
 3             return ;
 4         int Index = 0;
 5         for (int i=0; i<nums.length; i++){
 6             if(0 != nums[i]){
 7                 nums[Index++] = nums[i];
 8             }
 9         }
10         for(int i=Index; i<nums.length; i++){
11             nums[i] = 0;
12         }
13  
14     }

The use of two hands, the exchange position. Time complexity of O (n).

Thinking: can use two pointers, a first pointer always points to element 0 from left to right, the second pointer is a pointer to traverse, when the value is not 0 when traversing pointer, and this first element pointer to exchange the elements.

. 1  public  void moveZeroes ( int [] the nums) {
 2          // First pointer always points to the current element is 0 
. 3          int First = 0 ;
 . 4   
. 5          for ( int SECOND = 0; SECOND <nums.length; SECOND ++ ) {
 . 6              // 0 and non-0 exchange 
. 7              IF (the nums [SECOND] = 0! ) {
 . 8                  int TEMP = the nums [First];
 . 9                  the nums [First] = the nums [SECOND];
 10                  the nums [SECOND] = TEMP;
 . 11                  First ++ ;
 12             }
13         }
14     }

 

Guess you like

Origin www.cnblogs.com/wangyufeiaichiyu/p/11238506.html