Thursday, October 2, 2014

Without ten

Ques:
Return a version of the given array where all the 10's have been removed. The remaining elements should shift left towards the start of the array as needed, and the empty spaces a the end of the array should be 0. So {1, 10, 10, 2} yields {1, 2, 0, 0}

Ans:
public static int[] withoutTen(int[] nums) {
        int countof0 = 0;
        int swap = 0;
        int rep=0;
   //Replacing all tens with 0  
     for (int i=0;i<nums.length;i++){
            if(nums[i]==10){
                nums[i]=0;
            }
        }
// Identifying the number with zero
//Swapping the same with a non-zero
//Breaking out once identified and replaced

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                for (int j = i + 1; j < nums.length; j++) {
                    if (nums[j] != 0) {
                        swap = nums[j];
                        nums[j] = nums[i];
                        nums[i] = swap;
                        break;
                    }
                }
            }
        }
       
    return nums;
    }

No comments:

Post a Comment