Amazon OA

Remove Duplicates from unsorted array,它的错误在于9-10行k out of bound,改成下面这样就没问题了

 1 public class removeDuplicates {

 2     public static int[] remove(int[] arr){ 

 3 

 4         int end = arr.length;

 5 

 6         for(int i = 0; i < end; i++){

 7             for(int j = i + 1; j < end; j++){

 8                 if(arr[i] == arr[j]){                  

 9                     for(int k = j+1; k < end; k++){

10                         arr[k-1] = arr[k];

11                     }

12                     end--;

13                     j--;

14                 }

15             }

16         }

17 

18         int[] whitelist = new int[end];

19         for(int i = 0; i < end; i++){

20             whitelist[i] = arr[i];

21         }

22         System.out.print("new length is ");

23         System.out.println(end);

24         return whitelist;

25     }

26     

27     public static void main(String[] args) {

28         int[] arr = {3, 2, 1, 3, 2, 1, 3, 2, 1};

29         remove(arr);

30         for(int i:arr){

31             System.out.print(i);

32             System.out.print(", ");

33         }

34     }

35 }

Selection Sort Ascending order, 它的错误在于7行大于小于错误

 1     public static int[] doSelectionSort(int[] arr){

 2         

 3         for (int i = 0; i < arr.length-1; i++)

 4         {

 5             int index = i;

 6             for (int j = i + 1; j < arr.length; j++)

 7                 if (arr[j] < arr[index])

 8                     index = j;

 9       

10             int smallerNumber = arr[index]; 

11             arr[index] = arr[i];

12             arr[i] = smallerNumber;

13         }

14         return arr;

15     }

Selection Sort Dscending order, 他的错误在于第5行大于小于错误

 1     public static int[] doSelectionSort(int[] arr){ 

 2         for (int i=0; i<arr.length-1; i++) {

 3             int max = i;

 4             for (int j=1; j<arr.length; j++) {

 5                 if (max < arr[j]) {

 6                     max = j;

 7                 }

 8             }

 9             if (max != i) {

10                 int temp = arr[i];

11                 arr[i] = arr[max];

12                 arr[max] = temp;

13             }

14         }

15         return arr;

16     }

Reverse an int array, 它的问题在于第3行忘了-1

1 for (int i=0; i<arr.length/2; i++) {

2    int temp = arr[i]; 

3    arr[i] = arr[arr.length-1-i];

4    arr[arr.length-1-i] = temp;  

5 

6 }

Print Pattern, 打印11, 1111, 111111,中间需要换行,它的问题在于括号少打了

 

你可能感兴趣的:(OA)