剑指offer刷题记录 其他、回溯

剑指Offer(十一):二进制中1的个数

绝对最佳答案及分析:
public class Solution {
    public int NumberOf1(int n) {
        int count = 0;
        while(n!= 0){
            count++;
            n = n & (n - 1);
         }
        return count;
    }
}
答案正确:恭喜!您提交的程序通过了所有的测试用例
分析一下代码: 这段小小的代码,很是巧妙。
如果一个整数不为0,那么这个整数至少有一位是1。如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0,原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。其余所有位将不会受到影响。
举个例子:一个二进制数1100,从右边数起第三位是处于最右边的一个1。减去1后,第三位变成0,它后面的两位0变成了1,而前面的1保持不变,因此得到的结果是1011.我们发现减1的结果是把最右边的一个1开始的所有位都取反了。这个时候如果我们再把原来的整数和减去1之后的结果做与运算,从原来整数最右边一个1那一位开始所有位都会变成0。如1100&1011=1000.也就是说,把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0.那么一个整数的二进制有多少个1,就可以进行多少次这样的操作。

剑指Offer(十二):数值的整数次方

核心:是使用flag来表示exponent的正负号,

public class Solution {
    public double Power(double base, int exponent) {
        //数字的正数次方
        int flag=1;
        if(base==0)
            return 0;
        if(exponent<0){
            exponent=-exponent;
            flag=0;
            
        }
        double result=1;
        for(int i=0;i<exponent;i++){
            result*=base;
        }   
        
        if(flag==1){
            return result;
        }else{
            return result=1/result;
        }
        
  }
}

剑指Offer(十九):顺时针打印矩阵

import java.util.ArrayList;
public class Solution {
    ArrayList<Integer> list=new ArrayList<Integer>();
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        int rows=matrix.length;   /矩阵的行数
        int cols=matrix[0].length; 矩阵的列数
        int start=0;
        while(rows>start*2&&cols>start*2){
            shundayin(matrix,rows,cols,start);
            start++;
        }
        return list;
    }
    
    
    public void shundayin(int[][] matrix,int rows,int cols,int start){
        
        /首先从左到右进行遍历
        for(int i=start;i<cols-start;i++){
            list.add(matrix[start][i]);
        }
        
        //接着从右到下进行遍历
        for(int j=start+1;j<rows-start;j++){
            list.add(matrix[j][cols-start-1]);
        }
        //接着从下到左进行遍历
        for(int k=cols-start-2;k>=start&&rows-start-1!=start;k--){
            list.add(matrix[rows-start-1][k]);
        }
        //接着从左到上开始比遍历
        for(int n=rows-start-2;n>start&&cols-start-1!=start;n--){
            list.add(matrix[n][start]);
        }
        
    }
}

剑指Offer(二十九):最小的K个数

//方法一:冒泡排序

public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> al = new ArrayList<Integer>();
        if (k > input.length) {
			return al;
		}
		for (int i = 0; i < k; i++) {
			for (int j = 0; j < input.length - i - 1; j++) {
				if (input[j] < input[j + 1]) {
					int temp = input[j];
					input[j] = input[j + 1];
					input[j + 1] = temp;
				}
			}
			al.add(input[input.length - i - 1]);
		}
		return al;
    }

//大根堆的方式:

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> list=new ArrayList<Integer>();
        if(input.length==0||input==null||input.length<k){
            return list;
        }

        
        for(int i=(k-1)/2;i>=0;i--){
            Adjust(input,i,k-1);
        }
        
        for(int i=k;i<input.length;i++){
            if(input[0]>input[i]){
                input[0]=input[i];
                Adjust(input,0,k-1);                
            }
        }
        
        for(int i=0;i<k;i++){
            list.add(input[i]);
        }
        return list;
    }
    
    
    ///构建一个大根堆
    public void Adjust(int[] input,int start,int end){
        int temp=input[start];
        int child=start*2+1;
        
        while(child<=end){
            
            if(child+1<=end&&input[child]<input[child+1])
                child++;
            
            if(input[child]<temp)
                break;
            
            input[start]=input[child];
            start=child;
            child=start*2+1;
        }
        input[start]=temp;
    }
}

//大根堆 注释

 1     //构建大根堆:将array看成完全二叉树的顺序存储结构
 2     private int[] buildMaxHeap(int[] array){
 3         //从最后一个节点array.length-1的父节点(array.length-1-1)/2开始,直到根节点0,反复调整堆
 4         for(int i=(array.length-2)/2;i>=0;i--){ 
 5             adjustDownToUp(array, i,array.length);
 6         }
 7         return array;
 8     }
 9     
10     //将元素array[k]自下往上逐步调整树形结构
11     private void adjustDownToUp(int[] array,int k,int length){
12         int temp = array[k];   
13         for(int i=2*k+1; i<length-1; i=2*i+1){    //i为初始化为节点k的左孩子,沿节点较大的子节点向下调整
14             if(i<length && array[i]<array[i+1]){  //取节点较大的子节点的下标
15                 i++;   //如果节点的右孩子>左孩子,则取右孩子节点的下标
16             }
17             if(temp>=array[i]){  //根节点 >=左右子女中关键字较大者,调整结束
18                 break;
19             }else{   //根节点 <左右子女中关键字较大者
20                 array[k] = array[i];  //将左右子结点中较大值array[i]调整到双亲节点上
21                 k = i; //【关键】修改k值,以便继续向下调整
22             }
23         }
24         array[k] = temp;  //被调整的结点的值放人最终位置
25     }    

剑指Offer(三十一):整数中1出现的次数(从1到n整数中1出现的次数)

方法一:使用字符串的形式 (推荐)

public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
		int count=0;
    	StringBuffer s=new StringBuffer();
    	for(int i=1;i<n+1;i++){
    		 s.append(i);
    	}
    	String str=s.toString();
    	for(int i=0;i<str.length();i++){
    		if(str.charAt(i)=='1')
    			count++;
    	}
    	return count;
    }
}

方法二:非常经典的暴力破解法

public int NumberOf1Between1AndN_Solution(int n) {
    int count = 0;
    for(int i=0; i<=n; i++){
        int temp = i;
        //如果temp的任意位为1则count++
        while(temp!=0){
            if(temp%10 == 1){
                count++;
            }
            temp /= 10;
        }
    }
    return count;
}

方法三:观察规律法



/*
设N = abcde ,其中abcde分别为十进制中各位上的数字。
如果要计算百位上1出现的次数,它要受到3方面的影响:百位上的数字,百位以下(低位)的数字,百位以上(高位)的数字。
① 如果百位上数字为0,百位上可能出现1的次数由更高位决定。比如:12013,则可以知道百位出现1的情况可能是:100~199,1100~1199,2100~2199,,...,11100~11199,一共1200个。可以看出是由更高位数字(12)决定,并且等于更高位数字(12)乘以 当前位数(100)。
② 如果百位上数字为1,百位上可能出现1的次数不仅受更高位影响还受低位影响。比如:12113,则可以知道百位受高位影响出现的情况是:100~199,1100~1199,2100~2199,,....,11100~11199,一共1200个。和上面情况一样,并且等于更高位数字(12)乘以 当前位数(100)。但同时它还受低位影响,百位出现1的情况是:12100~12113,一共114个,等于低位数字(113)+1。
③ 如果百位上数字大于1(2~9),则百位上出现1的情况仅由更高位决定,比如12213,则百位出现1的情况是:100~199,1100~1199,2100~2199,...,11100~11199,12100~12199,一共有1300个,并且等于更高位数字+1(12+1)乘以当前位数(100)。
*/ 
public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
        int count = 0;//1的个数
        int i = 1;//当前位
        int current = 0,after = 0,before = 0;
        while((n/i)!= 0){           
            current = (n/i)%10; //高位数字
            before = n/(i*10); //当前位数字
            after = n-(n/i)*i; //低位数字
            //如果为0,出现1的次数由高位决定,等于高位数字 * 当前位数
            if (current == 0)
                count += before*i;
            //如果为1,出现1的次数由高位和低位决定,高位*当前位+低位+1
            else if(current == 1)
                count += before * i + after + 1;
            //如果大于1,出现1的次数由高位决定,//(高位数字+1)* 当前位数
            else{
                count += (before + 1) * i;
            }    
            //前移一位
            i = i*10;
        }
        return count;
    }
}

剑指Offer(三十三):丑数

//首先这道题目,不能用暴力破解的方法

public class Solution {
    public int GetUglyNumber_Solution(int index) {
        if(index<=0){
            return 0;
        }
        
        int[] arr=new int[index];
        int t2=0,t3=0,t5=0;
        arr[0]=1;
        int temp;
        for(int i=1;i<index;i++){
            temp=Math.min(2*arr[t2],Math.min(3*arr[t3],5*arr[t5]));
            arr[i]=temp;
            while(arr[t2]*2<=temp) t2++;
            while(arr[t3]*3<=temp) t3++;
            while(arr[t5]*5<=temp) t5++;
        }
           
        return arr[index-1];
    }
}

剑指Offer(四十一):和为S的连续正数序列

import java.util.ArrayList;
public class Solution {
    public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
        //存放结果
        ArrayList<ArrayList<Integer> > result = new ArrayList<>();
        //两个起点,相当于动态窗口的两边,根据其窗口内的值的和来确定窗口的位置和大小
        int plow = 1,phigh = 2;
        while(phigh > plow){
            //由于是连续的,差为1的一个序列,那么求和公式是(a0+an)*n/2
            int cur = (phigh + plow) * (phigh - plow + 1) / 2;
            //相等,那么就将窗口范围的所有数添加进结果集
            if(cur == sum){
                ArrayList<Integer> list = new ArrayList<>();
                for(int i=plow;i<=phigh;i++){
                    list.add(i);
                }
                result.add(list);
                plow++;
            //如果当前窗口内的值之和小于sum,那么右边窗口右移一下
            }else if(cur < sum){
                phigh++;
            }else{
            //如果当前窗口内的值之和大于sum,那么左边窗口右移一下
                plow++;
            }
        }
        return result;
    }
}

剑指Offer(四十二):和为S的两个数字

//夹逼,从两头到中间

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
       ArrayList<Integer> list=new ArrayList<Integer>();
       if(array.length==0||array==null){
           return list;
       }
        
        int start=0;
        int end=array.length-1;
        while(start<end){
            int current=array[start]+array[end];
            if(current==sum){
                list.add(array[start]);
                list.add(array[end]);
                return list;
            }else if(current<sum){
                start++;
            }else{
                end--;
            }
        }
        return list;
    }
}

剑指Offer(四十五):扑克牌顺子

1、排序
2、计算所有相邻数字间隔总数
3、计算0的个数
4、如果2、3相等,就是顺子
5、如果出现对子,则不是顺子

import java.util.Arrays;
public class Solution {
    public boolean isContinuous(int [] numbers) {
        if(numbers.length==0||numbers==null)
            return false;
        int length=numbers.length;
        int ZeroOfNumber=0;
        int IntervalOfNumber=0;
        Arrays.sort(numbers);
        for(int i=0;i<length-1;i++){
            if(numbers[i]==0){
                ZeroOfNumber++;
                continue;
            }
            
            if(numbers[i]==numbers[i+1])
                return false;
            
            IntervalOfNumber+=numbers[i+1]-numbers[i]-1;
            
        }
        if(ZeroOfNumber>=IntervalOfNumber){
            return true;
        }
       return false;
    }
}

剑指Offer(四十六):孩子们的游戏(圆圈中最后剩下的数)

public class Solution {
    public int LastRemaining_Solution(int n, int m) {
        if(m<1||n<1){
            return -1;
        }
        
        //针对于这个题,首先捋一下思路;n:表示数组的大小 m:表示 
        /用数组模拟链表,定义一个环,如果到m,则设置为-1;如果遇到-1则跳过;
        
        int[] a=new int[n];   /定义一个数组模拟环
        
        int i=-1,step=0,count=n;
        
        while(count>0){
            i++;
            if(i>=n) i=0;
            
            if(a[i]==-1) continue;
            step++;
            
            if(step==m){
                a[i]=-1;
                step=0;
                count--;
            }
        }
        return i;
    }
}

剑指Offer(四十七):求1+2+3+…+n

解题思路:
1.需利用逻辑与的短路特性实现递归终止。 2.当n==0时,(n>0)&&((sum+=Sum_Solution(n-1))>0)只执行前面的判断,为false,然后直接返回03.当n>0时,执行sum+=Sum_Solution(n-1),实现递归计算Sum_Solution(n)public int Sum_Solution(int n) {
    	int sum = n;
    	boolean ans = (n>0)&&((sum+=Sum_Solution(n-1))>0);
    	return sum;
    }

&&就是逻辑与,逻辑与有个短路特点,前面为假,后面不计算。

剑指Offer(四十八):不用加减乘除的加法

public class Solution {
    public int Add(int num1,int num2) {
        while (num2!=0) {
            int temp = num1^num2;
            num2 = (num1&num2)<<1;
            num1 = temp;
        }
        return num1;
    }
}

链接:https://www.nowcoder.com/questionTerminal/59ac416b4b944300b617d4f7f111b215
来源:牛客网

首先看十进制是如何做的: 5+7=12,三步走
第一步:相加各位的值,不算进位,得到2。
第二步:计算进位值,得到10. 如果这一步的进位值为0,那么第一步得到的值就是最终结果。

第三步:重复上述两步,只是相加的值变成上述两步的得到的结果2和10,得到12。

同样我们可以用三步走的方式计算二进制值相加: 5-101,7-111 第一步:相加各位的值,不算进位,得到010,二进制每位相加就相当于各位做异或操作,101^111。

第二步:计算进位值,得到1010,相当于各位做与操作得到101,再向左移一位得到1010,(101&111)<<1。

第三步重复上述两步, 各位相加 010^1010=1000,进位值为100=(010&1010)<<1。
继续重复上述两步:1000^100 = 1100,进位值为0,跳出循环,1100为最终结果。

剑指Offer(五十四):字符流中第一个不重复的字符

Solution: Java版的,使用一个HashMap来统计字符出现的次数,同时用一个ArrayList来记录输入流,每次返回第一个出现一次的字符都是在这个ArrayList(输入流)中的字符作为key去map中查找。

import java.util.*;
public class Solution {
    HashMap<Character, Integer> map=new HashMap();
    ArrayList<Character> list=new ArrayList<Character>();
    //Insert one char from stringstream
    public void Insert(char ch)
    {
        if(map.containsKey(ch)){
            map.put(ch,map.get(ch)+1);
        }else{
            map.put(ch,1);
        }
        
        list.add(ch);
    }
    
  	//return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {	char c='#';
    	for(char key : list){
            if(map.get(key)==1){
                c=key;
                break;
            }
        }
        
        return c;
    }
}

剑指Offer(六十三):数据流中的中位数

import java.util.Comparator;
import java.util.PriorityQueue;
public class Solution {

    /首先定义一个 最小堆  即升序
    PriorityQueue<Integer> minHeap=new PriorityQueue();    //定义最小堆 
    /接着定义一个 最大堆  即降序
    PriorityQueue<Integer> maxHeap=new PriorityQueue<Integer>(21,new Comparator<Integer>(){    //定义最大堆
        public int compare(Integer o1,Integer o2){
            return o2-o1;
        }
    });
    int count=0;
    public void Insert(Integer num) {
        if(count%2==1){     /当为偶数的时候,插入小根堆
            maxHeap.offer(num);
            int max=maxHeap.poll();
            minHeap.offer(max);
        }else{          当为奇数时候,插入大根堆
            minHeap.offer(num);
            int min=minHeap.poll();
            maxHeap.offer(min);
        }
        count++;
    }

    public Double GetMedian() {
        if(count%2==0){
            return new Double(maxHeap.peek()+minHeap.peek())/2;
        }else{
            return new Double(maxHeap.peek());
        }
    }


}

剑指Offer(六十四):滑动窗口的最大值

//经典的暴力破解的方法

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
        ArrayList<Integer> list=new ArrayList<Integer>();
        if(num.length==0||num==null||(num.length<size)||size==0)
            return list;
        
        for(int i=0;i<num.length-size+1;i++){
            int temp=num[i];
            for(int j=i+1;j<i+size;j++){
                if(temp<num[j])
                    temp=num[j];
            }
            list.add(temp);
        }
        return list;
    }
}

//使用一个队列来解决,让O(kn)变为O(n)

import java.util.*;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
        /*
        用一个双端队列,队列第一个位置保存当前窗口的最大值,当窗口欢动一次
        1.判断当前最大值是否过期
        2.新增加的值从队尾开始比较,把所有比他小的值丢掉
        */
        
        ArrayList<Integer> res=new ArrayList<Integer>();     //定义一个数组,来添加程序
        if(size==0) return res;                              //返回size的大小
        int begin;
        LinkedList<Integer> q=new LinkedList<Integer>();     //定义一个双边链表
        for(int i=0;i<num.length;i++){
            begin=i-size+1;
            if(q.isEmpty()){
                q.add(i);             加进去的是下标
            }else if(begin>q.peekFirst())   /判断当前值是否过期 
                q.pollFirst();
            
            while((!q.isEmpty())&&num[q.peekLast()]<=num[i])
                q.pollLast();
            q.add(i);
            if(begin>=0){
                res.add(num[q.peekFirst()]);
            }
        }
        return res;
    }
}

回溯法(两道)

(一):矩阵中的路径【回溯法】
占坑,以后写
(二):机器人的运动范围【回溯法】
占坑,以后写

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值