Sunday, September 21, 2014

3 appears in the array exactly 3 times

Ques: Given an array of ints, return true if the value 3 appears in the array exactly 3 times, and no 3's are next to each other.

Ans:
package countofthreenotnnext;
public class CountofthreenotnNext {

     public static void main(String[] args) {
             int[] nums = {3,2,3};
        System.out.println("Output=" + haveThree(nums));
    }

    public static boolean haveThree(int[] nums) {
        int count = 0;
        boolean mark = false;
        int[] trackpos = new int[nums.length];
        int pos = 0;
        if (nums.length > 2) {
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == 3) {
                    count++;
                    pos = pos + i;
                    trackpos[count - 1] = i;
                             }
                          }

            for (int i = 0; i < 3; i++) {
            }
            if ((trackpos[1] - trackpos[0]) == 2 && (trackpos[2] - trackpos[1]) == 2) {
                mark = true;
            }

          
        }
     return (count == 3) && mark ? true : false;
    }
}
 

No comments:

Post a Comment