2020-09-22

58同城的笔试

1. 实现出基本的计算器(类似,实现的功能不一样,原题要求是空格就合并,例如(1 5)–>(15))

我就不写了。直接参考大佬的吧,为大佬打一波广告~~~。

东哥

2. 计算1~n的元素的二进制中1的个数,并返回数组

这个是一个经典的算法了,但无奈本人是渣渣,没有遇到过,但是这种思路一点就破。多读书多看报少吃零食多睡觉。

利用了之前的数据对如今的数据的更新,和f(n) = f(n-1) + f(n-2)的推导类似。


import org.junit.Test;

import java.util.Arrays;

public class CountOneInNum {
    /*
    * 举例 f(5) = f(4) + f(1), 注意2的次方都是一个1,而且是最高位,f(5) = 1 + f(1), f(6) = 1 + f(2)直到f(8) = 1
    * */
    public int[] countBits(int num) {
        int[] res = new int[num+1];
        int pow2 = 1;
        int before = 1;
        for (int i = 1; i <=num; i++) {
            if (i == pow2) {
                before = res[i] = 1;
                pow2 = 1 << pow2;//进制的转换
            } else{
                res[i] = res[before] + 1;//1就是有2^0;
                before += 1;//控制住的是数组的前一个的位置的。
            }
        }
        return res;
    }

    @Test
    public void test() {
        System.out.println(Arrays.toString(countBits(5)));
    }

3. 对两个有序数组的共有的元素找出,并返回列表

思路:其实还是很好想到的,对数据的二分法的寻找。


import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;

public class Main3 {
    public ArrayList<Integer> mergerArrays (ArrayList<Integer> arrayA, ArrayList<Integer> arrayB) {
        // write code here use binary search
        ArrayList<Integer> res = new ArrayList<>();
        int aSize = arrayA.size();
        int bSize = arrayB.size();
        int index = 0;
        for (int i = 0; i < aSize; i++) {
            int tmp = arrayA.get(i);
            while(index<bSize) {
                int compare = arrayB.get(index);
                int right = bSize;
                int mid = index + (right - index) / 2;
                if (compare > tmp) {
                    break;
                } else if(compare == tmp) {
                    res.add(tmp);
                } else{
                    if (tmp > arrayB.get(mid)) {
                        index = mid+1;
                    } else if (tmp == arrayB.get(mid)) {
                        res.add(tmp);
                    } else if (tmp < arrayB.get(mid)) {
                        right = mid - 1;
                    }
                }
                index++;
            }
        }
        return res;
    }

    @Test
    public void test(){
        ArrayList<Integer> arr1 = new ArrayList(Arrays.asList(-5,0,6,8,9,10));
        ArrayList<Integer> arr2 = new ArrayList(Arrays.asList(0,8,9,11,15));
        System.out.println(mergerArrays(arr1, arr2).toString());
    }

求求你给个offer吧~~~菜鸡流下了泪水。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值