public static void main(String[] args) { int[] a = { 3, 5, 8, 6, 5, 4, 2, 1 }; List<Integer> list = new ArrayList<Integer>(); Arrays.sort(a); for (int i : a) { System.out.print(i); } for (int i = a.length - 1; i > 0; i--) { if (a[i] != a[i - 1]) { list.add(a[i]); }
代码要求是给一个数组排序,去掉重复数字后输出,原代码输出的顺序是从大到小,注释部分是我自己写的,想按从小到大输出,但是提示数组越界Exception,高手指点一下原因,另外,“list.add(a[0]);”这一句的作用是什么,求指教 [最优解释] int[] a = { 3, 5, 8, 6, 5, 4, 2, 1 }; List<Integer> list = new ArrayList<Integer>(); Arrays.sort(a); for (int i : a) { System.out.print(i); } System.out.println(" " + a.length + list.size()); for (int i = 0; i < a.length - 1; i++) //i < a.length - 1,要不然i+1还超出数组的索引 { if (a[i] != a[i + 1]) { list.add(a[i]); } } /* list.add(a[0]); */ //加上数组最后一个元素 list.add(a[a.length-1]);//加上数组最后最后一个元素,for循环运算不到 System.out.print("重新整理后的顺序是"); for (int j = 0; j < list.size(); j++) { System.out.print(list.get(j) + " "); } LZ要的是这个吧, [其他解释] 最后给一个完整的代码吧
public static void main(String[] args) { int[] a = { 3, 5, 8, 6, 5, 4, 2, 1, 1, 8 }; List<Integer> list = new ArrayList<Integer>(); Arrays.sort(a); for (int i : a) { System.out.print(i); }
System.out.println(" " + a.length); for (int i = 0; i < a.length - 1; i++) { if (a[i] != a[i + 1]) { list.add(a[i]); } //这里,最后两个数的比较,相同的话,你的代码就没有问题了。 // 不同的话,就需要将最后一个元素添加到list集合中 if (i == a.length - 2 && a[i] != a[1 + 1]) { list.add(a[i + 1]); } } // list.add(a[0]);? System.out.print("重新整理后的顺序是"); for (int j = 0; j < list.size(); j++) { System.out.print(list.get(j) + " "); } }
[其他解释] public static void main(String[] args) { int[] a = { 3, 5, 8, 6, 5, 4, 2, 1 }; List<Integer> list = new ArrayList<Integer>(); Arrays.sort(a); for (int i : a) { System.out.print(i); } for (int i = a.length - 1; i > 1; i--) { if (a[i] != a[i - 1]) { list.add(a[i]); }
import java.util.*; public class ArrayTest3 { public static void main(String[] args) { int[] a = { 3, 5, 8, 6, 5, 4, 2, 1 }; List<Integer> list = new ArrayList<Integer>(); Arrays.sort(a); for (int i : a) { System.out.print(i); } for (int i = a.length - 1; i > 0; i--) { if (a[i] != a[i - 1]) { list.add(a[i]); }
for (int i = a.length - 1; i > 0; i--) { if (a[i] != a[i - 1]) { list.add(a[i]); } } 对于数组的排序你可以查API文档,直接用sort方法排序: sort() public static void sort(char[] a)对指定的 char 型数组按数字升序进行排序。该排序算法是一个经过调优的快速排序法,改编自 Jon L. Bentley 和 M. Douglas McIlroy 合著的 Engineering a Sort Function", Software-Practice and Experience Vol. 23(11) P. 1249-1265 (November 1993)。此算法在许多数据集上提供 n*log(n) 性能,这导致其他快速排序会降低二次型性能。