This is an easy problem with the description being:
You are given an integer array nums. Transform nums by performing the following operations in the exact order specified:
Replace each even number with 0.
Replace each odd numbers with 1.
Sort the modified array in non-decreasing order.
Return the resulting array after performing these operations.
There is two ways of getting it solved. First and as simple as can be, you iterate, identify and replace the numbers with 0 and 1 if even or odd and then you sort your array before returning it:
class Solution {
public int[] transformArray(int[] nums) {
final int[] response = replaceEvenWithZeroOddWithOne(nums);
Arrays.sort(response);
return response;
}
public boolean isEven(final int num) {
return num % 2 == 0; // & can be used as well
}
public int[] replaceEvenWithZeroOddWithOne(final int[] nums) {
final int[] response = new int[nums.length];
for(int i=0;i<nums.length;i++){
response[i] = isEven(nums[i]) ? 0 : 1;
}
return response;
}
}
Runtime: 2ms, faster than 59.68% of Java online submissions.
Memory Usage: 44.70 MB, less than 95.92% of Java online submissions.
is not bad, and you can reuse the methods there, but there is a way to do everything inside a for loop, that would be using two pointers for the even and the odd:
class Solution {
public int[] transformArray(int[] nums) {
int even = 0;
int odd = nums.length - 1;
final int[] response = new int[nums.length];
for(int i=0;i<nums.length;i++){
if(isEven(nums[i])) {
response[even] = 0;
even++;
} else {
response[odd] = 1;
odd--;
}
}
return response;
}
public boolean isEven(final int num) {
return num % 2 == 0; // & can be used as well
}
}
Runtime: 1ms, faster than 100.00% of Java online submissions.
Memory Usage: 45.03 MB, less than 39.26% of Java online submissions.
This is much faster than the previous one, not as clean, but better in performance as you can see on the runtime numbers if you compare with previous solution.
That’s it! If there is anything thing else to discuss feel free to drop a comment, if I missed anything let me know so I can update accordingly.
Until next post! :)
Top comments (0)