找出两个数组之间的重复元素: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] + " ");
}
}