算法 - 数组

 找出两个数组之间的重复元素:map.get()

<span style="font-size:14px;">import java.util.*;
public class Test {
	public static void main(String[] args) {
		int a[] = {1,2,3,4,5};
		int b[] = {4,5,6,7,8};
		Map map = new HashMap();
		for(int i=0;i<a.length;i++){
			map.put(a[i],a[i]);
		}
		for(int j=0;j<b.length;j++){
			<span style="color:#ff0000;">if(map.get(b[j]) != null)</span>
				System.out.print(b[j] + " ");
		}
	}
}</span>


颠倒数组:a[i] = a[n-1-i]

import java.util.*;
public class Test {
	public static void main(String[] args) {
		int a[] = {1,2,3,4,5};
		int temp;
		int n = a.length;
		for(int i=0;i<n/2;i++){
			temp = a[i];
			<span style="color:#ff0000;">a[i] = a[n-1-i];</span>
			a[n-1-i] = temp;
		}
		for(int i=0;i<n;i++){
			System.out.print(a[i] + " ");
		}
	}	
}

寻找第K大:快速选择排序

public class Test {

	static int K = 5;
	static int a[] = {1,9,2,8,3,7,4,6,5};
	static int n = a.length;
	
	public static void main(String[] args) {
		sort(0, n-1);
	}
	public static void sort(int left, int right){
		if(left > right) // 退出递归
			return;
		
		int i = left; // 左标
		int j = right; // 右标
		int base = a[left]; // 基准数
		int temp;
		
		while(i<j){
			while(a[j]>base && i<j) // 先从右向左
				j--;
			while(a[i]<=base && i<j) // 不能忘了等号
				i++;
			if(i<j){  // 必须增加判断,由于自增i和j的大小关系可能已经改变
				temp = a[i];
				a[i] = a[j];
				a[j] = temp;
			}
		}
		
		a[left] = a[i]; // 将base放置在对应位置
		a[i] = base;

		if(i == (n-K)){
			System.out.println("Kth = " + a[i]);
			return;
		}
		if(i < (n-K)) // 选择递归
			sort(i+1, right);
		if(i > (n-K))
			sort(left, i-1);
	}
}


合并两个有序数组:++

public class Test {
	public static void main(String[] args) {
		int[] a = {1,3,5};
		int[] b = {2,4,6,8,9};
		int[] c = new int[a.length + b.length];
		int i = 0;
		int j = 0;
		int k = 0;
		
		while(i<a.length && j<b.length){
			if(a[i] < b[j]){
				c[k] = a[i];
				<span style="color:#ff0000;">k++;i++;</span>
			}
			else{
				c[k] = b[j];
				<span style="color:#ff0000;">k++;j++;</span>
			}
		}
		<span style="color:#ff0000;">while(i<a.length)</span>
			c[k++] = a[i++];
		<span style="color:#ff0000;">while(j<b.length)</span>
			c[k++] = b[j++];
		for(int l=0;l<c.length;l++)
			System.out.print(c[l] + " ");
	}
}


















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值