比如:[1, 2, 3, 3, 2, 2, 6, 7, 8, 9] 中 2 or 3
分析:这道题目,实现比较容易,方法也不少,但要用最小的空间复杂度来看的话, 和充分考虑一下数据的下标和数据元素值的特点,比如如果把第 i 个位置放的值是 i,不是的情况做交换,去循环对比。
时间复杂度O(n),空间复杂度可到常量级
测试代码如下:
public static void main(String[] args) { int n=10; List<Integer> list = new ArrayList<Integer>(); for(int i=0;i<n;i++){ list.add(new Random().nextInt(10));// //打印[1,10)先闭后开区间的随机值 } System.out.println("list is "+list); Integer [] arrays =list.toArray(new Integer[list.size()]); System.out.println("arrays is "+Arrays.toString(arrays)); System.out.println("arrays[0] is "+arrays[0]); for(int i=0;i<n ;i++){ if(arrays[i]==i){ continue; } if(arrays[i] == arrays[arrays[i]] ){ System.err.println("i is "+i+", arrays["+i+"] is "+arrays[i]+",arrays[arrays["+i+"]] is "+arrays[arrays[i]]); }else{ System.out.println("exchange i is "+i+", arrays["+i+"] is "+arrays[i]+" , arrays[arrays["+i+"]] is "+arrays[arrays[i]]); exchange(arrays,i,arrays[i]); } System.out.println("----------------------------------------------->arrays is "+Arrays.toString(arrays)); } System.out.println("end arrays is "+Arrays.toString(arrays)); //打印[1,10]闭区间的随机值 int x = 1; int y = 10; for(int i = 0;i<10;i++){ System.out.println(new Random().nextInt(y + 1 - x) + x); }} private static void exchange(Integer []arrays,int a ,int b){ int temp = arrays[a]; arrays[a] = arrays[b]; arrays[b] = temp;}
原文地址:https://www.cnblogs.com/xuzhujack/p/12189341.html
时间: 2024-11-05 16:08:40