顺时针翻转矩阵90
public void rotate(int[][] matrix) {
// Start typing your Java solution below
// DO NOT write main() function
int n = matrix.length;
for(int i = 0; i < n/2; i++){
for(int j = n - 1; j >=n/2; j--){
int tmp=matrix[i][j];
matrix[i][j]=matrix[n-j-1][i];
matrix[n-j-1][i]=matrix[n-i-1][n-j-1];
matrix[n-i-1][n-j-1]=matrix[j][n-i-1];
matrix[j][n-i-1]=tmp;
}
}
}
求x的n次方
public double pow(double x, int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(n == 0){
return 1;
}
if(n == 1){
return x;
}
if(n < 0){
x = 1/x;
n = -n;
}
if(n % 2 == 1){
double result = pow(x,(n-1) >> 1);
return x*result*result;
}else{
double result = pow(x,n >> 1);
return result*result;
}
}
swap the node pair
public ListNode swapPairs(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
if(head != null){
ListNode cur = head;
ListNode curNext = cur.next;
while(cur != null && curNext != null){
int val = cur.val;
cur.val = curNext.val;
curNext.val = val;
cur = curNext.next;
if(cur != null){
curNext = cur.next;
}
}
}
return head;
}
reverse k-group
public ListNode reverseKGroup(ListNode head, int k) {
// Start typing your Java solution below
// DO NOT write main() function
if(head == null){
return head;
}
//如果要求逆置的步长为1,则直接返回该链表
if(k == 1){
return head;
}
ListNode cur = head;
//定位到要逆置的位置
for(int i = 1; i < k; i++){
if(cur.next == null){
return head;
}
cur = cur.next;
}
//从头开始到cur结束,逆置链表
ListNode start = head;
ListNode temp = null;
//逆置链表的新的尾结点
ListNode last = start;
while(start != cur){
ListNode startNext = start.next;
start.next = temp;
temp = start;
start = startNext;
}
//递归的逆置剩下的链表
last.next = reverseKGroup(start.next,k);
cur.next = temp;
return cur;
}
remove the Nth from the end of the list
public ListNode removeNthFromEnd(ListNode head, int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(head == null){
return head;
}
ListNode cur = head;
for(int i = 0; i < n; i++){
if(cur == null){
//n is invalid,return the original list
return head;
}
cur = cur.next;
}
if(cur == null){
return head.next;
}
ListNode start = head;
while(cur.next != null){
start = start.next;
cur = cur.next;
}
start.next = start.next.next;
return head;
}