1. 程式人生 > >筆試程式設計經典(leetcode線上程式設計)

筆試程式設計經典(leetcode線上程式設計)

題目描述

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

程式碼:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
   public int run(TreeNode root) {
		return find(root);
	}
	
	private int find(TreeNode root){
		if(root==null){
			return 0;
		}
		if(root.left==null){
			return find(root.right)+1;
		}
		if(root.right==null){
			return find(root.left)+1;
		}
		return Math.min(find(root.left), find(root.right))+1;
	}
}

題目描述

Evaluate the value of an arithmetic expression inReverse Polish Notation.

Valid operators are+,-,*,/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
程式碼:
import java.util.Stack;
public class Solution {
   public  int evalRPN(String[] tokens) {
		int length=tokens.length;
		if(length==0)
			return 0;
		Stack<Integer> stack=new Stack<Integer>();
		for(int i=0;i<length;i++){
			if(tokens[i].equals("+")||tokens[i].equals("-")||tokens[i].equals("*")||tokens[i].equals("/")){
				if(tokens[i].equals("+")){
					int a=stack.pop();
					int b=stack.pop();
					int temp=b+a;
					stack.push(temp);
				}else if(tokens[i].equals("-")){
					int a=stack.pop();
					int b=stack.pop();
					int temp=b-a;
					stack.push(temp);
				}else if(tokens[i].equals("*")){
					int a=stack.pop();
					int b=stack.pop();
					int temp=b*a;
					stack.push(temp);
				}else{
					int a=stack.pop();
					int b=stack.pop();
					int temp=b/a;
					stack.push(temp);
				}
			}else{
				stack.push(Integer.valueOf(tokens[i]));
			}
		}
		return stack.peek();
	}
}

題目描述

Given a binary tree, return the postordertraversal of its nodes' values.

For example:
Given binary tree{1,#,2,3},

   1
    \
     2
    /
   3

return[3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

程式碼:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.ArrayList;
public class Solution {
  private ArrayList<Integer> list;
	public ArrayList<Integer> postorderTraversal(TreeNode root) {
		list=new ArrayList<Integer>();
		if(root==null){
			return list;
		}
		find(root);
		return list;
	}
	private void find(TreeNode root){
		if(root==null){
			return;
		}
		TreeNode left=root.left;
		TreeNode right=root.right;
		find(left);
		find(right);
		list.add(root.val);
	}

}

題目描述

Given a binary tree, return the preordertraversal of its nodes' values.

For example:
Given binary tree{1,#,2,3},

   1
    \
     2
    /
   3

return[1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

程式碼:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.ArrayList;
public class Solution {
   private ArrayList<Integer> list;
	public ArrayList<Integer> preorderTraversal(TreeNode root) {
		list=new ArrayList<Integer>();
		if(root==null){
			return list;
		}
		find(root);
		return list;
	}
	private void find(TreeNode root){
		if(root==null){
			return;
		}
		TreeNode left=root.left;
		TreeNode right=root.right;
		list.add(root.val);
		find(left);
		find(right);
		return;
	}
}

題目描述

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given{1,2,3,4}, reorder it to{1,4,2,3}.


程式碼:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
import java.util.LinkedList;
public class Solution {//這題沒做好,時間複雜度比較高,空了再研究一下
   public  void reorderList(ListNode head) {
		if(head==null||head.next==null){
			return;
		}
		LinkedList<ListNode> linkedList=new LinkedList<ListNode>();
		while(head!=null){
			linkedList.add(head);
			head=head.next;
		}
		LinkedList<ListNode> linkedList2=new LinkedList<ListNode>();
		int cnt=1;
		int size=linkedList.size();
		int index1=0,index2=size-1;
		for(int i=0;i<size;i++){
			if(cnt%2==0){
				linkedList2.add(linkedList.get(index2--));
			}else{
				linkedList2.add(linkedList.get(index1++));
			}
			cnt++;
		}
		head=null;
		head=linkedList2.get(0);
		ListNode phead=head;
		for(int i=1;i<linkedList2.size();i++){
			ListNode node=linkedList2.get(i);
			phead.next=node;
			phead=phead.next;
		}
		phead.next=null;
	}
}

題目描述

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

Follow up:
Can you solve it without using extra space?

程式碼:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
   public ListNode detectCycle(ListNode head) {
		if(head==null){
			return null;
		}
		ListNode slow=head;
		ListNode fast=head;
		while(fast!=null&&fast.next!=null){
			fast=fast.next.next;
			slow=slow.next;
			if(fast==slow){
				ListNode phead=head;
				while(phead!=slow){
					phead=phead.next;
					slow=slow.next;
				}
				return slow;
			}
		}
		return null;
	}

}

題目描述

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

程式碼:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {//判斷連結串列是否存在環
    public boolean hasCycle(ListNode head) {
		if(head==null){
			return false;
		}
		ListNode fast=head;
		ListNode slow=head;
		while(fast!=null&&fast.next!=null){
			fast=fast.next.next;
			slow=slow.next;
			if(fast==slow){
				return true;
			}
		}
		return false;
	}
}


題目描述

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

程式碼:
public class Solution {//強大的位運算
    public int singleNumber(int[] A) {
		int sum=0;
		for(int i=0;i<A.length;i++){
			sum^=A[i];
		}
		return sum;
	}
}

題目描述

There are N children standing in a line. Each child is assigned a rating value.

You are giving candies to these children subjected to the following requirements:

  • Each child must have at least one candy.
  • Children with a higher rating get more candies than their neighbors.

What is the minimum candies you must give?

程式碼:
public class Solution {
    public int candy(int[] ratings) {
		int length=ratings.length;
		if(length==0){
			return 0;
		}
		int []dp=new int[length];
		for(int i=0;i<length;i++){
			dp[i]=1;
		}
		for(int i=1;i<length;i++){
			if(ratings[i]>ratings[i-1]){
				dp[i]=dp[i-1]+1;
			}
		}
		for(int i=length-1;i>=1;i--){
			if(ratings[i]<ratings[i-1]&&dp[i]>=dp[i-1]){
				dp[i-1]=dp[i]+1;
			}
		}
		int sum=0;
		for(int i=0;i<length;i++){
			sum+=dp[i];
		}
		return sum;
		
	}
}

題目描述

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return[1,3,3,1].

Note:
Could you optimize your algorithm to use onlyO(k) extra space?

程式碼:
import java.util.ArrayList;
public class Solution {
   public ArrayList<Integer> getRow(int rowIndex) {
		ArrayList<Integer> list=new ArrayList<Integer>();
		rowIndex++;
		if(rowIndex==0){
			return list;
		}
		list.add(1);
		for(int i=1;i<rowIndex;i++){
			for(int j=i-1;j>=1;j--){
				list.set(j, list.get(j-1)+list.get(j));
			}
			list.add(1);
		}
		return list;
	}
}

題目描述

Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path1->2->3which represents the number123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / \
  2   3

The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.

Return the sum = 12 + 13 =25.



程式碼:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int sumNumbers(TreeNode root) {
		if(root==null){
			return 0;
		}
		return find(root,0);
	}
	private int find(TreeNode root,int sum){
		if(root==null){
			return 0;
		}
		sum=sum*10+root.val;
		TreeNode left=root.left;
		TreeNode right=root.right;
		if(left==null&&right==null){
			return sum;
		}
		return find(left, sum)+find(right, sum);
	}
}

題目描述

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given[100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is[1, 2, 3, 4]. Return its length:4.

Your algorithm should run in O(n) complexity.


程式碼:

import java.util.Arrays;
public class Solution {
   public  int longestConsecutive(int[] num) {
		if(num.length==0){
			return 0;
		}
		Arrays.sort(num,0,num.length);
		int MAX=1;
		int ans=1;
		for(int i=1;i<num.length;i++){
			if(num[i]-num[i-1]==1){
				ans++;
			}else if(num[i]-num[i-1]!=0){
				ans=1;
			}
			MAX=Math.max(MAX, ans);
		}
		return MAX;

	}
}