fork(5) 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 int getNumberSameAsIndex(int[] numbers) {
  11. if(numbers == null || numbers.length == 0) {
  12. return -1;
  13. }
  14.  
  15. int left = 0;
  16. int right = numbers.length - 1;
  17. while(left <= right) {
  18. int middle = left + ((right - left) >>> 1);
  19. if(numbers[middle] == middle) {
  20. return middle;
  21. }
  22.  
  23. if(numbers[middle] > middle) {
  24. right = middle - 1;
  25. }
  26. else {
  27. left = middle + 1;
  28. }
  29. }
  30.  
  31. return -1;
  32. }
  33.  
  34. // ----------------------- TEST CODE -----------------------
  35. private static void test(String testName, int[] numbers, int expected) {
  36. if(getNumberSameAsIndex(numbers) == expected) {
  37. System.out.println(testName + " passed.");
  38. }
  39. else {
  40. System.out.println(testName + " FAILED.");
  41. }
  42. }
  43.  
  44. private static void test1() {
  45. int[] numbers = {-3, -1, 1, 3, 5};
  46. int expected = 3;
  47. test("test1", numbers, expected);
  48. }
  49.  
  50. private static void test2() {
  51. int[] numbers = {0, 1, 3, 5, 6};
  52. int expected = 0;
  53. test("test2", numbers, expected);
  54. }
  55.  
  56. private static void test3() {
  57. int[] numbers = {-1, 0, 1, 2, 4};
  58. int expected = 4;
  59. test("test3", numbers, expected);
  60. }
  61.  
  62. private static void test4() {
  63. int[] numbers = {-1, 0, 1, 2, 5};
  64. int expected = -1;
  65. test("test4", numbers, expected);
  66. }
  67.  
  68. private static void test5() {
  69. int[] numbers = {0};
  70. int expected = 0;
  71. test("test5", numbers, expected);
  72. }
  73.  
  74. private static void test6() {
  75. int[] numbers = {10};
  76. int expected = -1;
  77. test("test6", numbers, expected);
  78. }
  79.  
  80. public static void main (String[] args) throws java.lang.Exception {
  81. test1();
  82. test2();
  83. test3();
  84. test4();
  85. test5();
  86. test6();
  87. }
  88. }
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
test1 passed.
test2 passed.
test3 passed.
test4 passed.
test5 passed.
test6 passed.