150.逆波兰表达式求值
import java.util.Stack;
public class stack150 {
public static void answerOne(String[] array) {
int[] stackNum = new int[array.length / 2 + 1]; //储存array里的的数字
int index = 0;
for (int i = 0; i < array.length; i++) {
String s = array[i];
if(s == "+")
stackNum[index-2] += stackNum[--index];
else if(s == "-")
stackNum[index-2] -= stackNum[--index];
else if(s == "*")
stackNum[index-2] *= stackNum[--index];
else if(s == "/")
stackNum[index-2] /= stackNum[--index];
else {
stackNum[index++] = Integer.parseInt(s);
index ++;
}
}
System.out.println(stackNum[0]);
}
public static void answerTwo(String[] array){
Stack<Integer> stackNum = new Stack<>();
Integer op1, op2;
for (int i = 0; i < array.length; i++) {
String s = array[i];
switch(s) {
case "+":
op1 = stackNum.pop(); //op1是运算符后面那个数
op2 = stackNum.pop(); //op2是运算符前面那个数
stackNum.push(op2 + op1);
break;
case "-":
op1 = stackNum.pop();
op2 = stackNum.pop();
stackNum.push(op2 - op1);
break;
case "*":
op1 = stackNum.pop();
op2 = stackNum.pop();
stackNum.push(op2 * op1);
break;
case "/":
op1 = stackNum.pop();
op2 = stackNum.pop();
stackNum.push(op2 / op1);
break;
default:
stackNum.push(Integer.valueOf(s));
break;
}
}
System.out.println(stackNum.pop());
}
}
169.多数元素
public class stack169 {
public static void answerOne(int[] array) {
int[] digitalNum = new int[array.length];
for (int i = 0; i < array.length; i++) {
digitalNum[i] = 0;
}
for (int i = 0; i < array.length; i++) {
int n = array[i];
digitalNum[n] ++;
}
int max = 0, indexMax = 0;
for (int i = 0; i < array.length; i++) {
if(max < digitalNum[i]){
max = digitalNum[i];
indexMax = i;
}
}
System.out.println(indexMax);
}
public static void answerTwo(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length - i - 1; j++) {
if(array[i] > array[j]){
int swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
}
System.out.println(array[array.length/2]); //排序后多数元素必在中间
}
public static void answerThree(int[] array){
int count = 1;
int group = array[0];
for (int i = 1; i < array.length; i++) {
if(count == 0){
count = 1;
group = array[i];
continue;
}
if(array[i] == group) //相同的则数量加一
count ++;
else //不同的则数量减一
count --;
}
System.out.println(group);
}
}
215.数组中第k个最大元素
public class stack215 {
public static void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public static void answersone(int[] nums, int k){
int index = nums.length - k;
int head = 0, tail = nums.length-1;
while(tail > head){
int x = nums[head];
int j = tail, i = head;
while(j > i){
while(nums[j] > x) {
j--;
if (j == head)
break;
}
swap(nums, i, j);
while(nums[i] < x) {
i++;
if (i >= j)
break;
}
swap(nums, i, j);
}
if(j < index)
head = j + 1;
else if(j > index)
tail = j - 1;
else if(j == index)
break;
}
System.out.println(nums[index]);
}
}