剑指offer java实现合集(3)第11~15题

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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值