11.二进制中1的个数
这个题很有意思,用到的知识点是:任何一个数和比他小一的数相与都会减少一个1的特性。
public class Solution {
public int NumberOf1(int n) {
int res = 0;
while(n!=0){
n=n&(n-1);
res++;
}
return res;
}
}
12.数值的整数次方
考察指数运算,分情况讨论。
public class Solution {
public double Power(double base, int exponent) {
double res = 1.0;
if(exponent>0){
while(exponent>0){
res=base*res;
exponent--;
}
}else if(exponent<0){
exponent = exponent*(-1);
while(exponent>0){
res=base*res;
exponent--;
}
res = 1/res;
}else{
res = 1.0;
}
return res;
}
}
13.调整数组顺序,使奇数位于偶数前面
我的做法是借用arraylist,先遍历一遍,添加奇数,再遍历一遍,添加偶数,最后将原来的数组覆盖。
import java.util.*;
public class Solution {
public void reOrderArray(int [] array) {
ArrayList<Integer> res = new ArrayList();
for(int i =0;i<array.length;i++){
if(array[i]%2==1){
res.add(array[i]);
}
}
for(int i=0;i<array.length;i++){
if(array[i]%2==0){
res.add(array[i]);
}
}
for(int i =0;i<array.length;i++){
array[i]=res.get(i);
}
}
}
14.链表中倒数第K个节点
我们用两个指针分别指向头结点,首先先让一个快指针移动K步,然后快慢指针同步移动,当快指针指向链表尾部的时候,慢指针所指向的就是倒数第K个节点。
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null){
return null;
}
ListNode fast = head;
ListNode slow = head;
while(k>0){
if(fast!=null){
fast=fast.next;
k--;
}else{
return null;
}
}
while(fast!=null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
15.链表反转
这道题很经典,很多算法如果能够链表反转来解决会容易很多,所以一定要牢记。
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode cur = head;
ListNode nHead = null;
ListNode pre = null;
while(cur!=null){
ListNode next = cur.next;
if(next==null){
nHead = cur;
}
cur.next = pre;
pre = cur;
cur = next;
}
return nHead;
}
}