【第一次使用java寫程序】有限羞澀

在這裏插入圖片描述

class Solution {
    public int rob(int[] nums) {
		int[] dp = new int[nums.length];
        if (nums.length==0){
            return 0;
        }else if(nums.length==1){
            return nums[0];
        }
        dp[0]=nums[0];
        dp[1]=Math.max(dp[0],nums[1]);
		int max=Math.max(dp[0],dp[1]);
		for(int i=2;i<nums.length;i++){
			dp[i]=Math.max(dp[i-1],dp[i-2]+nums[i]);
			max=Math.max(max,dp[i]);
			}
		return max;
    }
}

在這裏插入圖片描述

import java.util.Stack;
class MinStack {

    /** initialize your data structure here. */
    private Stack<Integer> stack; //定義一個棧
    private Stack<Integer> ministack;
    public MinStack() {
        stack = new Stack<>();
        ministack = new Stack<>();
    }
    
    public void push(int x) {
        stack.add(x);
        if (ministack.isEmpty() || ministack.peek() >= x) {
            ministack.add(x);
        }else{
            ministack.add(ministack.peek());
        }
    }
    
    public void pop() {
        if (!stack.isEmpty()) {
            stack.pop();
            ministack.pop();
        }
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return ministack.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

java.util.Stack的簡介

Stack是一種後進先出(LIFO)的結構,其繼承了Vector的基礎上拓展5個方法push()、pop()、peek()、empty()、search()而來
1、push(E):將item推入到棧中
2、pop() :將棧中的最頂一個item推出,並返回被推出的item
3、peek():返回棧中最頂的一個item,但不對其做任何操作
4、empty():判斷該棧是否爲空
5、search(Object):搜索某一個item在該棧中的位置【位置爲離棧頂最近的item與棧頂間距離】

PS:雖然Java有提供該類型的數據結構,但是官方推薦使用Deque【雙端隊列】,Deque提供更好的完整性和一致性,應該優先使用。

import java.util.Stack;

import org.junit.Before;
import org.junit.Test;

/**
 * Stack(棧)繼承了Vector類,底層實現是數組。 
 * 此處只介紹了Stack自己定義的方法,父類中的方法不再一一介紹。
 */
public class TestStack {

    // 定義一個棧
    Stack<String> stack;

    @Before
    public void before() {
        // 實例化棧變量
        stack = new Stack<String>();

        // add方法向棧中添加元素,添加成功返回true
        stack.add("1");
        stack.add("2");
        stack.add("3");
        stack.add("4");
        stack.add("5");

        // push方法向棧中添加元素,返回結果是當前添加的元素
        stack.push("a");
        stack.push("b");
        stack.push("c");
        stack.push("d");
        stack.push("e");

        // push和add都是向棧中添加元素,底層實現也是一樣的,都是先將Vector擴容,再添加

    }

    // pop方法移除並返回棧頂元素,如果是空棧,會拋出異常:EmptyStackException
    @Test
    public void test1() {
        String pop = stack.pop();
        System.out.println(pop); // e
        System.out.println(stack); // [1, 2, 3, 4, 5, a, b, c, d]
    }

    // peek方法獲取棧頂元素,但並不移除,如果是空棧,會拋出異常:EmptyStackException
    @Test
    public void test2() {
        String peek = stack.peek();
        System.out.println(peek); // e
        System.out.println(stack); // [1, 2, 3, 4, 5, a, b, c, d, e]
    }

    // empty方法檢查棧是否是空棧
    @Test
    public void test3() {
        boolean isEmpty = stack.empty();
        System.out.println(isEmpty); // false
    }

    // search方法查看某元素在棧中的位置,計數從1開始
    @Test
    public void test4() {
        int index = stack.search("1");
        System.out.println(index); // 10
    }

}
public class Test {

public static void main(String[] args){
Stack<String> stack = new Stack<>();
System.out.println("數量:"+stack.size());
stack.push("100");
stack.push("200");
stack.push("300");
for(int i = 0; i <stack.size(); i++){
System.out.println("stack值:"+stack.get(i));
}
System.out.println("數量:"+stack.size());
List<String> stack_list = stack.subList(0,2);
for(String str : stack_list){
System.out.println("stack_list截取值:"+str);
}
System.out.println("搜索100結果:"+stack.search("300"));
}
}

ArrayList初始化的4種方法

In the last post we discussed about class ArrayList in Java and it’s important methods. Here we are sharing multiple ways to initialize an ArrayList with examples.

Method 1: Initialization using Arrays.asList

 
ArrayList<Type> obj = new ArrayList<Type>(
        Arrays.asList(Object o1, Object o2, Object o3, ....so on));
Example:
 
import java.util.*;
public class InitializationExample1 {
   public static void main(String args[]) {
       ArrayList<String> obj = new ArrayList<String>(
        Arrays.asList("Pratap", "Peter", "Harsh"));
      System.out.println("Elements are:"+obj);
   }
}

Output:

Elements are:[Pratap, Peter, Harsh]

Method 2: Anonymous inner class method to initialize ArrayList

複製代碼
Syntax:

ArrayList<T> obj = new ArrayList<T>(){{
           add(Object o1);
           add(Object o2);
           add(Object o3);
                   ...
                   ...
           }};
Example:

import java.util.*;
public class InitializationExample2 {
   public static void main(String args[]) {
       ArrayList<String> cities = new ArrayList<String>(){{
           add("Delhi");
           add("Agra");
           add("Chennai");
           }};
      System.out.println("Content of Array list cities:"+cities);
   }
}

複製代碼

Output:

Content of Array list cities:[Delhi, Agra, Chennai]

Method3: Normal way of ArrayList initialization

複製代碼
Syntax:

ArrayList<T> obj = new ArrayList<T>();
       obj.add("Object o1");
       obj.add("Object o2");
       obj.add("Object o3");
                        ...
                        ...
Example:

import java.util.*;

public class Details {
   public static void main(String args[]) {
       ArrayList<String> books = new ArrayList<String>();
       books.add("Java Book1");
       books.add("Java Book2");
       books.add("Java Book3");
      System.out.println("Books stored in array list are: "+books);
   }
}

Output:

Books stored in array list are: [Java Book1, Java Book2, Java Book3]

Method 4: Use Collections.ncopies

Collections.ncopies method can be used when we need to initialize the ArrayList with the same value for all of its elements. Syntax: count is number of elements and element is the item value

ArrayList<T> obj = new ArrayList<T>(Collections.nCopies(count, element));
Example:

import java.util.*;

public class Details {
   public static void main(String args[]) {
       ArrayList<Integer> intlist = new ArrayList<Integer>(Collections.nCopies(10, 5));
      System.out.println("ArrayList items: "+intlist);
   }
}

Output:

ArrayList items: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]

參考原文鏈接:https://beginnersbook.com/2013/12/how-to-initialize-an-arraylist/

寫博客是爲了記住自己容易忘記的東西,另外也是對自己工作的總結,文章可以轉載,無需版權。希望儘自己的努力,做到更好,大家一起努力進步!

如果有什麼問題,歡迎大家一起探討,代碼如有問題,歡迎各位大神指正!

給自己的夢想添加一雙翅膀,讓它可以在天空中自由自在的飛翔!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章