Solving codingBat Post4 with one loop in Java -
the question solving this problem codingbat in java.
problem statement:
given non-empty array of ints, return new array containing elements original array come after last 4 in original array. original array contain @ least 1 4. note valid in java create array of length 0.
post4({2, 4, 1, 2}) → {1, 2}
post4({4, 1, 4, 2}) → {2}
post4({4, 4, 1, 2, 3}) → {1, 2, 3}
here solution:
public int[] post4(int[] nums) { int lastfour=-1; int[] post4={}; for(int i=nums.length-1;i>=0;i--) { if((nums[i]==4)) { lastfour=i; //find index of last 4 in array break; } } int newlen=(nums.length-lastfour)-1; post4=new int[newlen]; //reassign post4 array required length for(int j=0;j<newlen;j++) { post4[j]=nums[lastfour+1]; //assign values orig. array after last 4 lastfour++; } return post4; }
but have used 2 loops. should solved using @ max 1 loop. not use collections or wrappers classes.
- before iteration create result array, lets length 0.
- each time find
4
create new result array size based on index of4
, length ofnums
store rest of elements. - if number not
4
place in result array (don't place if result arrays length0
because means didn't find4
yet, or last element ofnums
array).
here example solution
public int[] post4(int[] nums) { int[] result = new int[0]; int j = 0; (int = 0; i<nums.length; i++){ if (nums[i] == 4) { result = new int[nums.length - i-1]; j=0; } else if (result.length>0) result[j++] = nums[i]; } return result; }
Comments
Post a Comment