题目描述
美团笔试,消除数组中相邻的,和为10的一对元素,返回消去这些元素后的数组长度。
例如:
数组2198,消除之后数组空了,输出0;
数组2198346,消除之后还剩3,输出1
解法
用栈存储不符合相邻和为10的元素。遍历原数组,如果栈顶和当前遍历到的元素之和为10,则出栈,否则入栈。
完整代码:
/*美团0404笔试
* 消除数组中相邻的和为10的元素
*/
public class Eleminatesum10 {
public static int eliminate10(int[] arr) {
//用栈
Stack<Integer> res = new Stack<Integer>();
res.add(arr[0]);
//遍历数组,如果栈顶和当前遍历到的元素之和为10,则出栈;否则入栈
for(int i = 1; i<arr.length; i++) {
if(!res.isEmpty() && (res.peek()+arr[i]==10)) {
res.pop();
continue;
}
res.add(arr[i]);
}
return res.size();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sets = in.nextInt();
String s = in.next();
int[] arr = new int[sets];
for(int i = 0; i<sets;i++){
int temp = Integer.parseInt(String.valueOf(s.charAt(i)));
arr[i] = temp;
}
System.out.println(eliminate10(arr));
}
}