转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6412505.html
心得:看到一道题,优先往栈,队列,map,list这些工具的使用上面想。不要来去都是暴搜,数组遍历。
11:Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
此题:给出一个数组,每个元素出现两次除了一个只出现一次,找到出现一次那个。
思路:这种有很明显映射关系的题:数—出现次数,第一时间就想到用map。
Map<Integer, Integer> map= new HashMap<Integer, Integer>(); int res = -1; for(int i:nums){ if(map.get(i)==null){ map.put(i, 1); }else{ map.put(i, 2); } } Set<Integer> keyset=map.keySet(); Iterator<Integer> iterator=keyset.iterator(); while(iterator.hasNext()){ int curr=iterator.next(); if(map.get(curr)==1){ res=curr; break; } } return res;
12:Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
此题:求二叉树的深度。
思路:与树有关的,第一时间想到队列、BFS、DFS这些关键字。
法一:BFS,利用队列(Java中LinkedList实现了Queue接口,用法同queue),一层层处理,处理一层,depth++;
public int maxDepth(TreeNode root) { int depth=0; LinkedList<TreeNode> linkedList=new LinkedList<TreeNode>(); linkedList.add(root); int current_count=1;
//while循环主要用来执行出队入队操作 while(!linkedList.isEmpty()){ TreeNode temp=linkedList.poll(); current_count--; if(temp.left!=null){ linkedList.add(temp.left); } if (temp.right!=null) { linkedList.add(temp.right); }
//current_count用来记录每一层的结点数目。然后执行current_count次循环处理完当前层结点,depth++。 if(current_count==0){ depth++; current_count=linkedList.size(); } } return depth; }
法二:二叉树的深度,最快的做法是DFS。实现DFS就一个思路:递归,返回值。
//定义边界 if(root==null){ return 0; }else{ //递归 int m=maxDepth(root.left); int n=maxDepth(root.right); //确定递归的返回值 return m>n?m+1:n+1; }
13:Sum of Two Integers
alculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
此题:求两整数和,但不能用运算符+/-。
思路:位运算的应用。
【leetcode】solution in java——Easy3
原文:http://www.cnblogs.com/ygj0930/p/6412505.html