Skip to content

Commit fe5f6d3

Browse files
committed
现在我们有一个int数组,请你找出数组中每个元素的下一个比它大的元素。
给定一个int数组A及数组的大小n,请返回一个int数组,代表每个元素比他大的下一个元素,若不存在则为-1。保证数组中元素均为正整数。 测试样例:
1 parent 92a7650 commit fe5f6d3

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

src/NextElement.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
* 现在我们有一个int数组,请你找出数组中每个元素的下一个比它大的元素。
3+
* 给定一个int数组A及数组的大小n,请返回一个int数组,代表每个元素比他大的下一个元素,
4+
* 若不存在则为-1。保证数组中元素均为正整数。
5+
* 测试样例:
6+
* [11,13,10,5,12,21,3],7
7+
* 返回:[13,21,12,12,21,-1,-1]
8+
*/
9+
public class NextElement {
10+
public int[] findNext(int[] A, int n) {
11+
// write code here
12+
int[] B=new int[n];
13+
for(int i=0;i<B.length;i++)
14+
B[i]=-1;
15+
for (int i = 0; i < A.length; i++) {
16+
for (int j = i+1; j < A.length; j++) {
17+
if (A[i]<A[j]) {
18+
B[i]=A[j];
19+
break;
20+
}
21+
}
22+
23+
}
24+
return B;
25+
}
26+
}

0 commit comments

Comments
 (0)