Ex 2_14 去掉数组中所有重复的元素..._第二次作业
2024-08-24 11:09:46
首先利用归并排序算法对数组进行排序,时间复杂度为O(nlogn),接着再利用时间复杂度为O(n) 的去重复算法去掉数组中的重复元素。总的时间复杂度为O(nlogn)。
(这题应该用分支算法解决)以下为分支算法
代码不是分支算法
package org.xiu68.ch02.ex2; public class Ex2_14 {
//基于分治法的归并排序算法
public static void main(String[] args) { int[] a=new int[]{5,5,4,4,3,3,3,2,2,1,1}; //先归并排序数组,时间复杂度为O(nlog2n)
mergeSort(a, a.length-1);
int min=a[0]-1; //去掉有序数组中的重复元素,时间复杂度为O(n)
removeSame(a); //总的时间复杂度为O(nlog2n)
for(int i=0;i<a.length;i++){
if(a[i]!=min)
System.out.print(a[i]+" ");
} } //一次归并,二并一
public static void merge(int[] start,int[] result,int s,int m,int t){
//s,m+1为两个有序序列的第一个记录,t为第二个序列的最后一个记录
int i=s;
int j=m+1;
int k=s; while(i<=m && j<=t)
if(start[i]<=start[j]) //取start[i]和start[j]的最小者放入result[k]
result[k++]=start[i++];
else
result[k++]=start[j++]; if(i<=m) //第一个序列没有遍历完
while(i<=m)
result[k++]=start[i++]; else //第二个序列没有遍历完
while(j<=t)
result[k++]=start[j++];
} //一趟排序,h为序列长度
public static void mergePass(int[] start,int[] result,int n,int h){
int i=0;
while(i<=n-2*h+1){
merge(start,result,i,i+h-1,i+2*h-1);
i+=2*h;
}
if(i<n-h+1)
merge(start,result,i,i+h-1,n);
else
for(int k=i;k<=n;k++)
result[k]=start[k];
} //归并排序
public static void mergeSort(int[] start,int n){
int h=1;
int[] result=new int[n+1];
while(h<n){
mergePass(start, result, n, h);
h=2*h;
mergePass(result, start, n, h);
h=2*h;
}
} //去掉数组中重复的部分
public static void removeSame(int[] a){
int min=a[0]-1; //把数组中的重复部分设置为min
for(int i=0;i<a.length;){
int j=i+1;
while(j<a.length && a[i]==a[j]){
a[j]=min;
j++;
}
i=j;
}//for
} }
最新文章
- 第19章 使用PXE+Kickstart部署无人值守安装
- 如何在Xilinx ISE中使用TCL提高工作效率
- OC 中的block使用
- Codeforces 492B B. Vanya and Lanterns
- spring+springmvc+mybaties整合实例
- Java 课程设计 ";Give it up";小游戏(团队)
- openstack pike 集群高可用 安装 部署 目录汇总
- UCS业务知识介绍
- [BZOJ2654] tree (kruskal &; 二分答案)
- 拿来主义:layPage分页插件的使用
- MySQL创建全文索引
- 洛谷 P1430 解题报告
- dom反转
- Java核心知识盘点(二)- 缓存使用
- CodeForces - 939A,解题报告
- python3.5 opencv3显示视频fps
- C# 多窗体之间方法调用
- Spark Streaming笔记
- Python 新建程序
- Linux Centos7中MySql安装
热门文章
- REST POST PUT差别
- kali渗透测试之缓冲区溢出实例-windows,POP3,SLmail
- 【python小练】0002
- C++中extern(转)
- LOJ #6261 一个人的高三楼
- F - Auxiliary Set HDU - 5927 (dfs判断lca)
- android gradle tools 3.X中dependencies, implementation和compile区别
- 第三节,CNN案例-mnist手写数字识别
- [转] 深入理解Batch Normalization批标准化
- P4553 80人环游世界