【Leetcode】496. Next Greater Element I

思路:

(1)flag标记是否找到待查找元素。

(2)遍历findNums,查找带查找元素。一旦找到,就把flag置为1,找到后,一旦该元素大于待查找元素,就把该元素加入result的对应位置

public class Solution {
    public int[] nextGreaterElement(int[] findNums, int[] nums) {
        int len = findNums.length;
        int[] result = new int[len];
        for (int i = 0; i < len; i++) {
            int j = 0, flag = 0, length = nums.length;
            for (; j < length; j++) {
                if (flag == 0 && nums[j] == findNums[i])
                    flag = 1;
                if(flag == 1 && nums[j] > findNums[i]) {
                    result[i] = nums[j];
                    break;
                }
            }
            if (j == length)
                result[i] = -1;
        }
        return result;
    }
}

Runtime:15ms

你可能感兴趣的:(Leetcode)