343、 Integer Break(给定整数n,将其分解成一些正数的和,求这些正数的乘积,求出乘积最大会是多少。。。) 基本原则:根据周长相等的长方形比正方形面积小来解,至于要分解成两个数还是三个数还是四个数的乘积呢。。。。循环吧。。。 代码如下:
public class Solution {
public int integerBreak(int n) {
int max=0;
for(int i=2;i<=n;i++){
int tmp = 1;
int first = n/i;
int tn = n-first;
tmp*=first;
for(int j=1;j<i;j++){
if(j==i-1){
tmp*=tn;
}else {
tmp*=first;
tn-=first;
}
}
max=tmp>max?tmp:max;
tmp = 1;
first = n/i+1;
tn = n-first;
tmp*=first;
for(int j=1;j<i;j++){
if(j==i-1){
tmp*=tn;
}else {
tmp*=first;
tn-=first;
if(tn<first)
j=i-2;
}
}
max=tmp>max?tmp:max;
}
return max;
}<br/>
}
133、 Clone Graph(深拷贝图结构,不能用原来的图里的任何引用哦!) 思路:很简单,深度优先搜索或者广度优先搜索,但是由于题目中的图结构中没有标记是否visited的标记变量,只能在搜索中添加一个记录型容器, 遍历过的点放到容器里面,下次再获取这个点的时候直接从容器中取出,不需要在深入遍历,这也是递归的结束条件,原本是没结束条件的,会栈区溢出。。。 代码如下:(这次也算是想到了深度优先和广度优先的新的一种结束控制条件了,学习一下哦~)
/**
- Definition for undirected graph.
- class UndirectedGraphNode {
-
int label;
-
List<UndirectedGraphNode> neighbors;
-
UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
- };
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node != null) {
Map<Integer, UndirectedGraphNode> record = new HashMap<Integer, UndirectedGraphNode>();
return dfs(node, record);
}
return null;
}
private UndirectedGraphNode dfs(UndirectedGraphNode node,
Map<Integer, UndirectedGraphNode> record) {
Integer t = new Integer(node.label);
if(record.containsKey(t)){
return record.get(t);
}
UndirectedGraphNode node2 = new UndirectedGraphNode(node.label);
// visited
record.put(t, node2);
for (int i = 0; i < node.neighbors.size(); i++) {
UndirectedGraphNode child = node.neighbors.get(i);
UndirectedGraphNode n1 = dfs(child,record);
node2.neighbors.add(n1);
}
return node2;
}
}
349、 Intersection of Two Arrays(呵呵,我刷题的顺序错了。。这题和第一题差不多,改个细节就行了。。。。)
public class Solution {
int max(int n,int m){
return n>m?n:m;
}
class Num{
public int num;
public boolean visited=false;
public Num(int n){
this.num=n;
}
}
public int[] intersection(int[] nums1, int[] nums2) {
int len = max(nums1.length,nums2.length);
Set<Integer> result = new HashSet<Integer>();
int pos=0;
Num[] n1 = new Num[nums1.length];
Num[] n2 = new Num[nums2.length];
for(int i=0;i<nums1.length;i++){
n1[i] = new Num(nums1[i]);
}
for(int i=0;i<nums2.length;i++){
n2[i] = new Num(nums2[i]);
}
for(int i=0;i<nums1.length;i++){
for(int j=0;j<nums2.length;j++){
if(n1[i].num==n2[j].num&&n2[j].visited==false&&n1[i].visited==false){
result.add(n2[j].num);
n2[j].visited=true;
n1[i].visited=true;
}
}
}
int[] arr = new int[result.size()];
int i=0;
Iterator<Integer> iterator = result.iterator();
while(iterator.hasNext()){
arr[i++]=iterator.next();
}
return arr;
}<br/>
}
345、 Reverse Vowels of a String(字符串逆序,只是加了个条件,只逆序字符串中的元音字母,其实都一样) 写得有点乱啊,之前以为只能用java.lang包下的类而已,什么容器什么的都不敢用,导致之前写的代码很有局限性,施展不开啊。。。 这几次发现可以了,但是我没去写import语句,可能他后台自动引入吧哈哈哈,先不管了反正能用就行~ 上代码:
public class Solution {
public String reverseVowels(String s) {
List<Integer> positions = new ArrayList<Integer>();
char[] vowels= new char[s.length()];
int pos=0;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (isVowels(s.charAt(i))) {
vowels[pos++]=s.charAt(i);
positions.add(i);
}
builder.append(s.charAt(i));
}
int left=0,right=pos-1;
while(left<right){
char tmp = vowels[left];
vowels[left] = vowels[right];
vowels[right]=tmp;
left++;
right--;
}
for(int i=0;i<positions.size();i++){
builder.setCharAt(positions.get(i), vowels[i]);
}
return builder.toString();
}
private boolean isVowels(char c) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
|| c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
return true;
return false;
}<br/>
}
344、 Reverse String(easy的题真是刷的快。。。)
public class Solution {
public String reverseString(String s) {
StringBuilder builder = new StringBuilder(s);
int left=0,right=s.length()-1;
while(left<right){
char tmp = builder.charAt(left);
builder.setCharAt(left,builder.charAt(right));
builder.setCharAt(right,tmp);
left++;
right--;
}
return builder.toString();
}<br/>
}
342、 Power of Four(判断是否是4的某次方,别忘了还有0次方。。。)
public class Solution {
public boolean isPowerOfFour(int num) {
if(num==4)return true;
if(num==1)return true;
while(num>=4){
if(num==4)return true;
if(num%4!=0)return false;
num/=4;
}
return false;
}<br/>
}
326、 Power of Three(和上题一样啊,判断3的某次方)
public class Solution {
public boolean isPowerOfThree(int n) {
if(n==3)return true;
if(n==1)return true;
while(n>=3){
if(n==3)return true;
if(n%3!=0)return false;
n/=3;
}
return false;
}<br/>
}
303、 Range Sum Query - Immutable(计算数组中指定下标的的和)
public class NumArray {
int[] nums;
public NumArray(int[] nums) {
this.nums=nums;
}
public int sumRange(int i, int j) {
int sum=0;
for(;i<=j&&i<nums.length;i++){
sum+=nums[i];
}
return sum;
}<br/>
}
258、 Add Digits(计算正数各位数字之和)
public class Solution {
public int addDigits(int num) {
while(num>=10){
int sum=0;
while(num>0){
sum+=num%10;
num/=10;
}
num=sum;
}
return num;
}<br/>
}
104、 Maximum Depth of Binary Tree(计算树的最深深度)
/**
- Definition for a binary tree node.
- public class TreeNode {
-
int val;
-
TreeNode left;
-
TreeNode right;
-
TreeNode(int x) { val = x; }
- }
*/
public class Solution {
public int maxDepth(TreeNode root) {
return dfs(root,0);
}
public int dfs(TreeNode node, int depth) {
if (node == null)
return depth;
TreeNode left = node.left;
TreeNode right = node.right;
int deepLeft = dfs(left, depth+1);
int deepRight = dfs(right, depth+1);
return deepLeft > deepRight ? deepLeft : deepRight;
}
}
226、 Invert Binary Tree(二叉树对称转换)
/**
- Definition for a binary tree node.
- public class TreeNode {
-
int val;
-
TreeNode left;
-
TreeNode right;
-
TreeNode(int x) { val = x; }
- }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null)
return null;
TreeNode tmp = root.left;
root.left=root.right;
root.right=tmp;
invertTree(root.left);
invertTree(root.right);
return root;
}<br/>
}
283、 Move Zeroes(把数组的0移到最后,不要复制数组,只在原数组上操作哦)
public class Solution {
public void moveZeroes(int[] nums) {
int pos = 0;
for (int i=0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[pos++]=nums[i];
}
}
for (; pos < nums.length; pos++) {
nums[pos] = 0;
}
}<br/>
}
237、 Delete Node in a Linked List(删除链表中的本节点)
/**
- Definition for singly-linked list.
- public class ListNode {
-
int val;
-
ListNode next;
-
ListNode(int x) { val = x; }
- }
*/
public class Solution {
public void deleteNode(ListNode node) {
node.val=node.next.val;
node.next=node.next.next;
}
}
100、 Same Tree(判断二叉树是否相等)
/**
- Definition for a binary tree node.
- public class TreeNode {
-
int val;
-
TreeNode left;
-
TreeNode right;
-
TreeNode(int x) { val = x; }
- }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null)
return true;
else if((p==null&&q!=null)||(p!=null&&q==null)){
return false;
}
return p.val==q.val&&isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}
}
242、 Valid Anagram(单词重组)
public class Solution {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length())return false;
StringBuilder builder = new StringBuilder(t);
int count=0;
for(int i=0;i<s.length();i++){
for(int j=0;j<builder.length();j++){
if(s.charAt(i)==builder.charAt(j)){
count++;
builder.deleteCharAt(j);
break;
}
}
}
return count==s.length();
}
}
171、 Excel Sheet Column Number(Excel的列号转换,实际就是26进制。。。)
public class Solution {
public int titleToNumber(String s) {
int sum=0;
for(int i=0;i<s.length();i++){
int val = s.charAt(i)-'A'+1;
sum = sum*26+val;
}
return sum;
}
}
169、 Majority Element(找数组中的众数,数量大于数组长度一半的)
public class Solution {
public int majorityElement(int[] nums) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++){
if(map.get(nums[i])==null){
map.put(nums[i],1);
}else {
map.put(nums[i],map.get(nums[i])+1);
}
if(map.get(nums[i])>nums.length/2)
return nums[i];
}
return -1;
}
}
217、Contains Duplicate(判断数组中是否有重复的元素,有的话返回true,否则返回false)
public class Solution {
public boolean containsDuplicate(int[] nums) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++){
if(map.get(nums[i])==null){
map.put(nums[i],1);
}else {
return true;
}
}
return false;
}
}
206、Reverse Linked List(链表逆序,把指针转向...)
/**
- Definition for singly-linked list.
- public class ListNode {
-
int val;
-
ListNode next;
-
ListNode(int x) { val = x; }
- }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null)return null;
ListNode pre=head,tmp=null;
head=head.next;
pre.next=null;
while(head!=null){
tmp=head;
head=head.next;
tmp.next=pre;
pre=tmp;
}
return pre;
}
}
13、 Roman to Integer(罗马数字转换) 面向对象编程:
public class Solution {
public class RomanN {
int value;
char c;
public RomanN(int value, char c) {
super();
this.value = value;
this.c = c;
}
public boolean moreThan(RomanN r) {
if (this.value > r.value)
return true;
else
return false;
}
}
public Map<Character, RomanN> init() {
Map<Character, RomanN> map = new HashMap<Character, RomanN>();
map.put('I', new RomanN(1, 'I'));
map.put('V', new RomanN(5, 'V'));
map.put('X', new RomanN(10, 'X'));
map.put('L', new RomanN(50, 'L'));
map.put('C', new RomanN(100, 'C'));
map.put('D', new RomanN(500, 'D'));
map.put('M', new RomanN(1000, 'M'));
return map;
}
public int romanToInt(String s) {
Map<Character, RomanN> map = init();
StringBuilder builder = new StringBuilder();
int sum = 0;
for (int i = 0; i < s.length()-1; i++) {
builder.append(s.charAt(i));
if (map.get(s.charAt(i)).moreThan(map.get(s.charAt(i + 1)))) {
int t = 0;
for (int j = builder.length() - 1; j >= 0; j--) {
if (map.get(builder.charAt(builder.length() - 1)).moreThan(
map.get(builder.charAt(j))))
t -= map.get(builder.charAt(j)).value;
else t += map.get(builder.charAt(j)).value;
}
sum+=t;
builder = new StringBuilder();
}
}
builder.append(s.charAt(s.length()-1));
int t = 0;
for (int j = builder.length() - 1; j >= 0; j--) {
if (map.get(builder.charAt(builder.length() - 1)).moreThan(
map.get(builder.charAt(j))))
t -= map.get(builder.charAt(j)).value;
else t += map.get(builder.charAt(j)).value;
}
sum+=t;
return sum;
}
}
235、Lowest Common Ancestor of a Binary Search Tree(二叉搜索树查找指定两个节点的最近公共祖先)
/**
- Definition for a binary tree node.
- public class TreeNode {
-
int val;
-
TreeNode left;
-
TreeNode right;
-
TreeNode(int x) { val = x; }
- }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(p.val<root.val&&q.val<root.val)
return lowestCommonAncestor(root.left,p,q);
if(p.val>root.val&&q.val>root.val)
return lowestCommonAncestor(root.right,p,q);
return root;
}
}
191、 Number of 1 Bits(计算Integer类型的二进制序列中的1的数量,其中int要看成unsigned类型。。。)
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
String s = Integer.toBinaryString(n);
int count=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='1')
count++;
}
return count;
}
}
231、Power of Two(判断是否是2的某次方)
public class Solution {
public boolean isPowerOfTwo(int num) {
if(num==2)return true;
if(num==1)return true;
while(num>=2){
if(num==2)return true;
if(num%2!=0)return false;
num/=2;
}
return false;
}
}
83、 Remove Duplicates from Sorted List(删除有序链表中的重复元素)
/**
- Definition for singly-linked list.
- public class ListNode {
-
int val;
-
ListNode next;
-
ListNode(int x) { val = x; }
- }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode n = head;
while(n!=null){
while(n.next!=null&&n.val==n.next.val){
n.next=n.next.next;
}
n=n.next;
}
return head;
}
}
263、 Ugly Number(判断Ugly数,只含有2,3,5质数因子的成为Ugly数)
public class Solution { public boolean isUgly(int n1) { if(n1==1) return true; if(n1==0) return false; //2 while(n1%2==0){ n1/=2; } //3 while(n1%3==0){ n1/=3; } //5 while(n1%5==0){ n1/=5; }
if(n1==1)return true;
else return false;
}
}
70、 Climbing Stairs(爬楼梯呵呵,踩坑了。。移到Easy的题。。) 第一个方案:数学组合公式计算(未解决,因为阶乘会导致int溢出。。。) public int zuhe(int m, int n) { int result = 1; for (int i = 1; i <= n; i++) { if (i > 1) { result = result / (i - 1) * (m - n + i); } else { result = result * (m - n + i); } } if (n != 0) result /= n; System.out.println("result=" + result); return result; }
public int climbStairs(int n) {
int sum = 0;
for (int i = 0; i <= n / 2; i++) {// i是2的个数
int t = zuhe(n - i, i);
System.out.println(t);
sum += zuhe(n - i, i);
}
return sum;
}
第二个方案:(二叉树递归搜索。。正解,答案都正确,但是递归层次太多导致超时。。。) public int climbStairsX(int n, int num) { if (n == 1) return 1 * num; if (n == 2) return 2 * num; int n1 = climbStairsX(n - 1, num); int n2 = climbStairsX(n - 2, num); return (n1 + n2) * num; }
public int climbStairs(int n) {
return climbStairsX(n, 1);
}
第三个方案:(这道题好好想啊,其实就是求斐波那契,用循环求斐波那契。。。) 怎么说呢? n=1的时候呢,只有一种方案, n=2的时候,有两个方案,1+1和2+0 n=3的时候呢,几个方案?根本不需要再列举了啊。。。就是n=1的方案再加上一步2和n=2的方案再加上一步1,不就是3步了吗。。。所以n=3的时候就是n=1的加上n=2的。。。这不就是斐波那契吗。。。 public class Solution {
public int climbStairs(int n) {
int s1=1,s2=1,tmp=1;
for(int i=2;i<=n;i++){
tmp=s1+s2;
s1=s2;
s2=tmp;
}
return tmp;
}
}
202、 Happy Number(快乐数,把数字的每个数位求平方和,以此类推无限循环下去,如果能得到平方和为1,停止循环,是happy number,如果陷入死循环,那就不是happy number)
public class Solution {
public boolean isHappy(int n) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
while(n!=1){
int sum=0;
while(n>0){
int t = n%10;
sum+=t*t;
n/=10;
}
if(map.get(sum)==null)
map.put(sum,1);
else {
return false;
}
n=sum;
}
return true;
}
}
141、 Linked List Cycle(检查链表是否有回环)
/**
- 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;
Map<ListNode,Integer> map = new HashMap<ListNode,Integer>();
while(head!=null){
if(map.get(head)==null){
map.put(head,1);
}else {
return true;
}
head = head.next;
}
return false;
}
}
121、 Best Time to Buy and Sell Stock(股价最佳收益) public class Solution {
public int max(int n,int m){
return n>m?n:m;
}
public int min(int n,int m){
return n<m?n:m;
}
//股价价格此起彼伏,不断记住当前的最大值即可,而每次到最低点就切换最低点,画个折线趋势图很好理解
public int maxProfit(int[] prices) {
if(prices.length<1)return 0;
int max = 0;//其实最大值
int low = prices[0];//从第一个价格开始
for(int i=1;i<prices.length;i++){
//根据当前找到的最小值递增上去找最大差值
low = min(low,prices[i]);//如果当前的价格比之前的最低价低,置换成当前的最低点,因为这个最低点之后的肯定是从这个点开始有利
max = max(max,prices[i]-low);//找到当前的位置,计算当前位置和当前的最低点的差值,和之前算过的最大值比较,取其大
}
return max;
}
}
21、 Merge Two Sorted Lists(归并排序,呵呵,太熟了。。。只是这次是链表,指针小心点就行)
/**
- Definition for singly-linked list.
- public class ListNode {
-
int val;
-
ListNode next;
-
ListNode(int x) { val = x; }
- }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null&&l2==null)return null;
if(l2==null) return l1;
if(l1==null) return l2;
ListNode head = null;
if(l1.val<l2.val){
head = l1;
l1=l1.next;
}
else {
head=l2;
l2=l2.next;
}
ListNode p = head;
while(l1!=null&&l2!=null){
if(l1.val<l2.val){
p.next=l1;
l1=l1.next;
p=p.next;
}else {
p.next=l2;
l2=l2.next;
p=p.next;
}
}
while(l1!=null){
p.next=l1;
l1=l1.next;
p=p.next;
}
while(l2!=null){
p.next=l2;
l2=l2.next;
p=p.next;
}
return head;
}
}
24、 Swap Nodes in Pairs(链表中更换相邻两个节点)
/**
- Definition for singly-linked list.
- public class ListNode {
-
int val;
-
ListNode next;
-
ListNode(int x) { val = x; }
- }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)return head;
ListNode first = head,second = head.next;
head = second;
first.next=second.next;
second.next=first;
ListNode p = first;
while(first.next!=null){
first = first.next;
if(first.next==null)
break;
second = first.next;
p.next=second;
first.next=second.next;
second.next=first;
p=first;
}
return head;
}
}
198、 House Robber(盗贼盗取房屋现金问题) 不习惯这种解法啊,用两个变量分别记住两种情况的最大值,并在循环过程中根据具体要求对两个最大值进行相应的变换,最后再通过这两个最大值得到最终结果,循环中两个最大值的迭代变换要好好理解,领悟 public class Solution {
public int max(int n,int m){
return n>m?n:m;
}
public int rob(int[] nums) {
if(nums.length<1)
return 0;
int n0=0;//上次没选的总价值
int n1=0;//上次有选的总价值
for(int i=0;i<nums.length;i++){
int tmp = n0;//缓存上次没选物品的价值,等会加上当前物品要用
n0=max(n0,n1);//不选当前的物品的最大值,就是之前的有选和没选的最大值
n1=tmp+nums[i];//有选当前物品的只能是上个物品没选的价值加上当前的价值
}//如此循环下去,n0一直是当前物品没选的价值,n1一直是有选当前物品的总价值
//最后一个物品有选没选的两个价值,其较大的就是最后的最大值
return max(n0,n1);
}
}
232、 Implement Queue using Stacks(用Stack去实现Queue的功能)
class MyQueue {
Stack<Integer> stack = new Stack<Integer>();
// Push element x to the back of queue.
public void push(int x) {
Stack<Integer> tmp = new Stack<Integer>();
while(!stack.isEmpty()){
int t = stack.pop();
tmp.push(t);
}
stack.push(x);
while(!tmp.isEmpty()){
int t = tmp.pop();
stack.push(t);
}
}
// Removes the element from in front of queue.
public void pop() {
stack.pop();
}
// Get the front element.
public int peek() {
return stack.peek();
}
// Return whether the queue is empty.
public boolean empty() {
return stack.isEmpty();
}
}
107、 Binary Tree Level Order Traversal II(层次遍历二叉树)
/**
- Definition for a binary tree node.
- public class TreeNode {
-
int val;
-
TreeNode left;
-
TreeNode right;
-
TreeNode(int x) { val = x; }
- }
*/
public class Solution {
public class Node {
TreeNode treenode;
int deep;
public Node(TreeNode node,int deep){
this.treenode=node;
this.deep=deep;
}
}
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<Node> list = new ArrayList<Node>();
int deep = travel(root,0,list);
List<List<Integer>> result = new ArrayList<List<Integer>>();
for(int d = deep;d>=1;d--){
List<Integer> ttt = new ArrayList<Integer>();
for(int i=0;i<list.size();i++){
if(d==list.get(i).deep){
ttt.add(list.get(i).treenode.val);
}
}
result.add(ttt);
}
return result;
}
public int travel(TreeNode root,int deep,List<Node> list){
if(root==null)return deep;
Node tmp = new Node(root,deep+1);
list.add(tmp);
int l = travel(root.left,deep+1,list);
int r = travel(root.right,deep+1,list);
return l>r?l:r;
}
}
27、 Remove Element(删除数组中的元素) public class Solution {
public int removeElement(int[] nums, int val) {
int len = nums.length;
int pos=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==val){
len--;
}else{
nums[pos++]=nums[i];
}
}
return len;
}
}
66、 Plus One(大数加法,竖式运算) public class Solution {
public int[] plusOne(int[] digits) {
digits[digits.length-1]++;
int plus = 0;
for(int i=digits.length-1;i>=0;i--){
if(i>0){
digits[i-1]+=digits[i]/10;
}else {
plus = digits[i]/10;
}
digits[i]%=10;
}
if(plus==0)return digits;
else {
int[] result = new int[digits.length+1];
result[0]=plus;
for(int i=0;i<digits.length;i++){
result[i+1]=digits[i];
}
return result;
}
}
}