fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13.  
  14. // boolean array
  15. boolean [] arr={false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true};
  16.  
  17. // Finding first occurence of T in the array (arr)
  18.  
  19. //Brute force : we'll use two loops ....O(N^2) TC....!
  20.  
  21. //Optimal force : we'll use Binary Search....
  22.  
  23. int idx=firstOccurence(arr);
  24. System.out.println("First occurence of T is on index :"+ idx);
  25. }
  26.  
  27. public static int firstOccurence(boolean[] arr){
  28. int start=0;
  29. int end=arr.length-1;
  30. int i=-1;
  31. while(start<=end){
  32. int mid = (start+end)/2;
  33. if(arr[mid]==false){
  34. start=mid+1;
  35. }else{
  36. i=mid;
  37. end=mid-1;
  38. }
  39. }
  40. return i;
  41. }
  42. }
Success #stdin #stdout 0.1s 55684KB
stdin
Standard input is empty
stdout
First occurence of T is on index :14