The WeakReference class, monitoring memory leak and garbage collection in a Java application

Image
 Below is a Stack implementation that uses an internal resizeable array structure.  public class MyStack< T > implements Stack< T > { private static final int CAPACITY = 100 ; private Object[] array ; private int pos = 0 ; public MyStack () { this . array = new Object[ CAPACITY ] ; } @Override public void push ( T item) { if ( pos >= array . length / 2 ) { Object[] newArray = new Object[ pos * 2 ] ; System. arraycopy ( array , 0 , newArray , 0 , array . length ) ; array = newArray ; } array [ pos ++] = item ; } @Override public T pop () { if (isEmpty()) { throw new RuntimeException( "empty stack" ) ; } @SuppressWarnings ( "unchecked" ) T item = ( T ) array [ pos - 1 ] ; pos -= 1 ; return item ; } @Override @SuppressWarnings ( "unchecked" ) public T peek...

Using XOR operator in bit manipulation problems

Problem description from LeetCode:

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

Input: [1,2,1,3,2,5] 
Output: [3,5]

Solution:

If we apply XOR to all the elements, the result is the XOR of the lonely integers. The next step is finding the two integers that produce the XOR result. 
To do that, we can use this trick:
The set bits of A XOR B  gives us which bits are different in A and B
After finding the last different set bit, we can dissect the numbers from the input. 

Source Code:

class Solution {
    
   public static int[] singleNumber(int[] nums) {
        int xor = 0;
        for (int num : nums) {
            xor ^= num;
        }
        int lastSetBit = lastSetBit(xor);

        int set1 = 0; int set2 = 0;
        for (int i = 0; i < nums.length; ++i) {

            if ((nums[i] & lastSetBit) == 0) {
                set1 ^= nums[i];
            } else {
                set2 ^= nums[i];
            }
        }

        return new int[]{set1, set2};
    }

    private static int lastSetBit(int xor) {

        int i = 0;
        for (; i < 32; ++i) {
            if ((xor & (1 << i)) != 0) {
                break;
            }
        }

        return (1 << i);
    }
    
}


Comments

Popular posts from this blog

Trie Data Structure and Finding Patterns in a Collection of Words

My Crappy Looking Solution to "Binary Tree Common Ancestor" Problem

A Graph Application in Java: Using WordNet to Find Outcast Words