Merge Sorted Array

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:

You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

public class MergeTwoSortedArrays{
    public void merge(int A[], int m, int B[], int n) {
        int len;
        len = m+n;
        int aindex = m-1;
        int bindex = n-1;
        int i=len-1;
        while(i>=0)
        {
            if(aindex<0)
            {
                A[i--]=B[bindex--];
            }
            else if(bindex<0)
            {
                A[i--]=A[aindex--];
            }
            else if(A[aindex]>B[bindex])
            {
                A[i--]=A[aindex--];
            }
            else if(A[aindex]<B[bindex])
            {
                A[i--]=B[bindex--];
            }
            else if(A[aindex]==B[bindex])
            {
                A[i--]=A[aindex--];
                A[i--]=B[bindex--];
            }

        }


    }
}

Majority Element

Problem

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

This problem can be solved in Linear time using Majority Vote Algorithm.

  • Time Complexity - O(n)
  • Space Complexity - O(1)
public class Solution {
    public int majorityElement(int[] num) {
       int cur=0;
       int counter=0;
     for(int i=0;i<num.length;i++)
     {
        if(counter==0){cur=num[i]; counter=1;}
        else if(counter!=00 && cur==num[i]) {counter++;}
        else {counter--;}
     }
     if(counter!=0) return cur;
     else return -1;

    }
}