451. 两两交换链表中的节点
给一个链表,两两交换其中的节点,然后返回交换后的链表。
样例
给出 1->2->3->4, 你应该返回的链表是 2->1->4->3。
AC
public ListNode swapPairs(ListNode head) {
ListNode CurHead=new ListNode(0);
CurHead.next=head;
head=CurHead;
while (head.next!=null&&head.next.next!=null){
ListNode CurNode=head.next,NextNode=head.next.next;
head.next=NextNode;
CurNode.next=NextNode.next;
NextNode.next=CurNode;
head=CurNode;
}
return CurHead.next;
}
453. 将二叉树拆成链表
将一棵二叉树按照前序遍历拆解成为一个假链表。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。
AC
public void flatten(TreeNode root){
if(root==null)
return;
Stack<TreeNode> stack=new Stack<>();
stack.push(root);
while(!stack.empty()){
TreeNode node =stack.pop();
if(node.right!=null)
stack.push(node.right);
if(node.left!=null)
stack.push(node.left);
node.left=null;
if(stack.empty())
node.right=null;
else
node.right=stack.peek();
}
}
491. 回文数
判断一个正整数是不是回文数。
回文数的定义是,将这个数反转之后,得到的数仍然是同一个数。
样例
11, 121, 1, 12321 这些是回文数。
23, 32, 1232 这些不是回文数。
AC
public class Solution {
/**
* @param num: a positive number
* @return: true if it's a palindrome or false
*/
public boolean isPalindrome(int num){
if(num==0)
return true;
int len=0;
int N=num;
while (N!=0){
len++;
N/=10;
}
int a[]=new int[len];
for(int i=0;i<len;i++){
a[i]=num%10;
num/=10;
}
for(int i=0,j=len-1;i<=j;i++,j--)
if(a[i]!=a[j])
return false;
return true;
}
}
514. 栅栏染色
我们有一个栅栏,它有n个柱子,现在要给柱子染色,有k种颜色可以染。 必须保证不存在超过2个相邻的柱子颜色相同,求有多少种染色方案。
样例
n = 3, k = 2, return 6
public class Solution {
/**
* @param n: non-negative integer, n posts
* @param k: non-negative integer, k colors
* @return: an integer, the total number of ways
*/
public int numWays(int n, int k) {
// write your code here
int dp[]={0,k,k*k,0};
if(n<=2)
return dp[n];
if(k==1)
return 0;
for(int i=2;i<n;i++){
dp[3]=(k-1)*(dp[1]+dp[2]);
dp[1]=dp[2];
dp[2]=dp[3];
}
return dp[3];
}
}
517. 丑数
写一个程序来检测一个整数是不是丑数。
丑数的定义是,只包含质因子 2, 3, 5 的正整数。比如 6, 8 就是丑数,但是 14 不是丑数以为他包含了质因子 7。
样例
给出 num = 8,返回 true。
给出 num = 14,返回 false。
public class Solution {
/**
* @param num: An integer
* @return: true if num is an ugly number or false
*/
public boolean isUgly(int num) {
// write your code here
if(num==0)
return false;
while (num%2==0)
num/=2;
while (num%3==0)
num/=3;
while (num%5==0)
num/=5;
if(num==1)
return true;
else return false;
}
}