c語言找出數組中重復的數字,筆試題:在整數數組中找到重復的數字

 2023-10-06 阅读 24 评论 0

摘要:題目描述: java編碼實現在整數數組中找到重復的數字,要求復雜度低于O(N*N) 解題思路: 我用兩種方法進行解答,其一是用桶的思想,其二是排序 程序代碼: public class Main {public static void main(String[] args) {int[] a = {

題目描述:
java編碼實現在整數數組中找到重復的數字,要求復雜度低于O(N*N)
解題思路:
我用兩種方法進行解答,其一是用桶的思想,其二是排序
程序代碼:

public class Main {public static void main(String[] args) {int[] a = {1,1,6,5,5,5,-10,-10};
//    int[] a = {1,1,1,6,5,5,10,10};
//    int[] a = {-5,-5,-8,-8};
//    int[] a = {5};int[] b = new int[110];int maxn = -(1<<31);int minn = (1<<31) - 1;System.out.print("原數據:");for (int i : a) {System.out.print(i + " ");}System.out.println("\n第一種時間復雜度大約是O(n)或O(數組中最大值減最小值)");// 找出數組中最大值和最小值for (int i = 0; i < a.length; i ++) {if (a[i] > maxn) {maxn = a[i];}if (a[i] < minn) {minn = a[i];}}// 將a數組的值,以索引的思想存到b數組中for (int i = 0; i < a.length; i ++) {b[a[i] - minn] ++;}// 遍歷b數組中的索引,找出出現次數大于1的for (int i = 0; i <= maxn - minn; i ++) {if (b[i] > 1) {System.out.print(i + minn + " ");}}System.out.println("\n第二種是先快排,然后找出出現多次的元素,再進行去重");// 如果數據差較大,先進行排序int len = a.length;int j = 0;if (len > 1) {quickSort(a,0,len - 1);for (int i = 1; i < len; i++) {if (a[i] == a[i-1]) {b[j ++] = a[i];}}}// 去重if (j > 0) {System.out.print(b[0]);for (int i = 1; i < j; i++) {if (b[i] != b[i - 1]) {System.out.print(" " + b[i]);}}}}static void quickSort(int a[],int left,int right) {int i, j, temp;i = left;j = right;if (i >= j) {return;}while (i < j) {while (i < j && a[j] >= a[left]) {j --;}while (i < j && a[i] <= a[left]) {i ++;}temp = a[i];a[i] = a[j];a[j] = temp;}temp = a[i];a[i] = a[left];a[left] = temp;quickSort(a,left,i - 1);quickSort(a,i + 1,right);}
}

c語言找出數組中重復的數字?運行結果:
在這里插入圖片描述

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/122858.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息