Bubble Sort Algorithm
This is kind of preliminary technique of sorting. And, this is the first…
September 03, 2020
Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
Example
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
We can keep a index variable which will keep a tab on all non-zero values.
On iteration, we can move each non-zero value to left side.
public void moveZeroes_simple(int[] nums) {
int left=0;
for (int i=0; i<nums.length; i++) {
if (nums[i] != 0) {
nums[left] = nums[i];
left ++;
}
}
//copy zeroes to remaining array
for (int i=left; i<nums.length; i++) {
nums[i] = 0;
}
}
Its O(n)
We can do a slight modification to above solution. The point where we just move non-zero value to left. We can do a swap as well.
public void moveZeroes(int[] nums) {
int left=0;
for (int i=0; i<nums.length; i++) {
if (nums[i] != 0) {
//swap
int t = nums[i];
nums[i] = nums[left];
nums[left] = t;
left ++;
}
}
}
Its O(n)
But, its better since we are not using another loop to copy zero.
This is kind of preliminary technique of sorting. And, this is the first…
Problem Statement Given a non-empty array of digits representing a non-negative…
This algorithm is very efficient one, and is classic example of Divide and…
Problem Statement You are given an array prices where prices[i] is the price of…
Problem Statement Given a signed integer, reverse digits of an integer. Return…
Problem Statement Replace all spaces in a string with ‘%20’ (three characters…
Introduction This post has the complete code to send email through smtp server…
Introduction In a normal email sending code from python, I’m getting following…
Introduction In one of my app, I was using to talk to . I have used some event…
Introduction So you have a Django project, and want to run it using docker image…
Introduction It is very important to introduce few process so that your code and…
Introduction In this post, we will see a sample Jenkin Pipeline Groovy script…