JAVA语言(数组简单算法)

一、在数组中删除一个数(这个数给定

//(1)在数组中删除一个数(这个数给定)
	public static void test(int key){
		int a[]={1,2,3,4,5,6,7,9,10};
		//删除后的新数组
		int b[]=new int[a.length-1];
		int count=0;
		for (int i = 0; i < a.length; i++) {
			if(a[i]==key){
				count=i;
				break;
			}	
		}
		for (int i=0; i < count; i++) {
			b[i]=a[i];
		}
		for (int i=count; i < b.length; i++) {
			b[i]=a[i+1];
		}
		//循环遍历新数组
		for (int i = 0; i < b.length; i++) {
			System.out.print(b[i]+"  ");
		}
	}

二、从数组a[]中删除删除元素key

//从数组a[]中删除删除元素key;
	public static void test1(int key, int a[]){
		int count =0;
		int[] b=new int[a.length-1];
		//f给代码中打个标记
		boolean f=false;
		for (int i = 0; i < a.length; i++) {
			//判断数组中是否有给定的元素key
			if (a[i]==key) {
			//记录key元素在数组中的下标位置	
				count=i;
				f=true;
				break;
			}
		}
		//如果数组中存在元素key,则进入以下代码,即f==true;
		if(f==true){
			for (int i = 0; i < count; i++) {
				b[i]=a[i];
			}
			for (int i = count; i < b.length; i++) {
				b[i]=a[i+1];
			}
			//循环遍历输出删除元素key后的产生的新数组
			for (int i = 0; i < b.length; i++) {
				System.out.print(b[i]+" ");
			}
		}else{
			System.out.println("数组中不存在"+key+"这个元素,请确认");
		}
	}

三、从数组中删除一个数(这个数的位置给定,即下标位置给定
1.b:原始数组
2.and:要删除的位置
3. 开辟一个新数组
4. 位置之前原样复制
5. 位置之后,错位复制
6. 返回新数组

	public static void test01(int and){
		int b[]={1,2,3,4,5,6,7};
		
		int c[]=new int [b.length-1];
		for (int i = 0; i < and; i++) {
			
			c[i]=b[i];
		}
//		for (int i = and; i <b.length-1; i++) {
//			c[i]=b[i+1];//此处下标的边界以数组c的空间长度确定
//		}
		//上下两个for循环都是为了确定and位置之后的元素如何复制到新数组c
		for (int i = and+1; i < b.length; i++) {
			c[i-1]=b[i];//此处下标的边界以数组b的空间长度确定
		}
		//循环遍历输出新的数组c
		for (int i = 0; i <c.length; i++) {
			System.out.print(c[i]+"  ");
		}
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dim_boy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值