the easy understanding way of use stack


  • 0
    W

    public int wiggleMaxLength(int[] nums) {
    int len = nums.length, i, max = 1;
    if ( len < 2) return len;

        Stack<Integer> st = new Stack<Integer>(); 
        boolean f = false;//false small,
        boolean first = false;
        st.add(nums[0]);
        for ( i = 1; i< len; i ++)
        {
            if (!first && nums[i] != st.peek() )
            {
                if ( nums[i] > st.peek() )
                    f = false;
                else 
                    f = true;
                st.add(nums[i]);
                first = true; 
            }
            else
            {
                if ( nums[i] == st.peek() ) 
                    continue;
                else if ( f )
                {
                    if ( nums[i] > st.peek() )
                        f = false;
                    else 
                        st.pop();
                    st.add(nums[i]);
                }
                else
                {
                    if ( nums[i] < st.peek() )
                        f = true;
                    else 
                        st.pop();   //13368156565
                    st.add(nums[i]);
                }
            } 
        }
        return st.size();
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.