面试算法

月伴飞鱼 2024-06-23 15:20:26
算法相关
支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者!

面试题17.01不用加号的加法

class Solution {
    public int add(int a, int b) {
        int m = a ^ b; //不进位加法
        int n = (a & b) << 1; //进位
        while (n != 0) {
            int temp = n ^ m;
            n = (m & n) << 1;
            m = temp;
        }
        return m;
    }
}

面试题17.14最小K个数

class Solution {
    public int[] smallestK(int[] arr, int k) {
        if (k >= arr.length) {
            return arr;
        }

        int low = 0;
        int high = arr.length - 1;
        while (low < high) {
            int pos = partition(arr, low, high);
            if (pos == k - 1) {
                break;
            } else if (pos < k - 1) {
                low = pos + 1;
            } else {
                high = pos - 1;
            }
        }

        int[] dest = new int[k];
        System.arraycopy(arr, 0, dest, 0, k);
        return dest;
    }

    private int partition(int[] arr, int low, int high) {
        int pivot = arr[low];
        while (low < high) {
            while (low < high && arr[high] >= pivot) {
                high--;
            }

            arr[low] = arr[high];
            while (low < high && arr[low] <= pivot) {
                low++;
            }
            arr[high] = arr[low];
        }
        arr[low] = pivot;
        return low;
    }
}

面试题16.06最小差

class Solution {

    public int smallestDifference(int[] a, int[] b) {
        long result = Integer.MAX_VALUE;
        Arrays.sort(a);
        Arrays.sort(b);

        for (int i = 0, j = 0; i < a.length && j < b.length; ) {
            result = Math.min(result, Math.abs((long) a[i] - b[j]));
            if (a[i] < b[j]) {
                i++;
            } else {
                j++;
            }
        }

        return (int) result;
    }
}

将驼峰命名转为小写下划线命名

LeetCode转化为leet_code,LeetHTTPBack转化为leet_http_back

# -*- coding: utf-8 -*-
def get_trans_name(text):
    length=len(text)
    lst=[]
    for i in range(length):
        # 前一个字母大写,后一个字母小写,将该字母从大写转换成小写
        if i+1<length and  text[i].isupper() and not text[i+1].isupper():
            lst.append(text[i].lower())
        else:
            lst.append(text[i])
        # 前一个字母是小写,后一个字母是大写的情景
        if not text[i].isupper() and i+1<length and text[i+1].isupper():
            lst.append("_")
        # 前两个字母是大写,后一个字母是小写的情景
        if text[i].isupper() and i+2<length and text[i+1].isupper() and not text[i+2].isupper():
            lst.append("_")
    return "".join(lst)
 
 
if __name__ == '__main__':
    print(get_trans_name("LeetCode"))
    print(get_trans_name("LeetHTTPBack"))

字符串相减

public class SubString {
    /**
     * 若a字符串表示的数字小于b字符串表示的数字则返回true
     *
     * @param a
     * @param b
     * @return
     */
    public static boolean isLess(String a, String b) {
        // 由于是大数,考虑转成字符串处理
        // 长度更长的字符串,数一定更大
        // 当长度一样的就去比较字典序
        if (a.length() == b.length()) {
            if (a.compareTo(b) < 0) {
                return true;
            } else if (a.compareTo(b) >= 0) {
                return false;
            }
        }
        return a.length() < b.length();
    }

    /**
     * 大数减小数
     * @param a
     * @param b
     * @return
     */
    public static String sub(String a, String b) {
        StringBuilder ans = new StringBuilder();
        int borrow = 0;
        int i = a.length() - 1, j = b.length() - 1;
        while (i >= 0 || j >= 0) {
            int x = i >= 0 ? (a.charAt(i) - '0') : 0;
            int y = j >= 0 ? (b.charAt(j) - '0') : 0;
            int z = (x - borrow - y + 10) % 10;

            ans.append(z);
            borrow = x - borrow - y < 0 ? 1 : 0;
            i--;
            j--;
        }
        ans.reverse();
        // 删除前导零,边界是 ans.length()-1, 防止当 ans 为 "0000" 时,清空
        // 121-120=001 需要删除前导0
        // 121-121=000 不能把所有 0 都删掉
        int pos = 0;
        while (pos < ans.length()-1 && ans.charAt(pos) == '0') {
            pos++;
        }
        return ans.toString().substring(pos);
    }

    /**
     * 给定两个字符串形式的非负整数num1和num2,计算它们的差
     * 注意:
     *  num1 和num2 都只会包含数字 0-9
     *  num1 和num2 都不包含任何前导零
     *  你不能使用任何內建 BigInteger 库
     * @param a
     * @param b
     * @return
     */
    public static String subString(String a, String b) {
        String res;
        if (isLess(a, b)) {
            res = sub(b, a);
            // 结果为 0 时,不加负号
            if (res != "0") {
                res = "-" + res;
            }
        } else {
            res = sub(a, b);
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(subString("121", "120"));
        System.out.println(subString("121", "121"));
    }
}

字符串相减(36进制)

public class Sub36 {
    public char getChar(int n) {
        if (n <= 9) {
            return (char)(n + '0');
        } else {
            return (char)(n - 10 + 'a');
        }
    }

    public int getInt(char c) {
        if (c >= '0' && c <= '9') {
            return c - '0';
        } else {
            return c - 'a' + 10;
        }
    }

    public String sub(String a, String b) {
        int borrow = 0;
        int i = a.length() - 1;
        int j = b.length() - 1;
        char[] ca = a.toCharArray();
        char[] cb = b.toCharArray();
        StringBuilder res = new StringBuilder();
        while (i >= 0 || j >= 0) {
            int x = i >= 0 ? getInt(ca[i]) : 0;
            int y = j >= 0 ? getInt(cb[i]) : 0;
            int z = (x - borrow - y + 36) % 36;
            res.append(getChar(z));
            borrow = x - borrow - y < 0 ? 1 : 0;
            i--;
            j--;
        }
        res.reverse();
        // 删除前导0。注意:循环条件是res.size()-1是为防止"0000"的情况
        int pos;
        for (pos = 0; pos < res.length() - 1; pos++) {
            if (res.charAt(pos) != '0') {
                break;
            }
        }
        return res.toString().substring(pos);
    }

    boolean isLess(String a, String b) {
        if (a.length() == b.length()) {
            return a.compareTo(b) < 0;
        }
        return a.length() < b.length();
    }

    public String subString(String num1, String num2) {
        if (isLess(num1, num2)) {
            String res = sub(num2, num1);
            return "-" + res;
        }
        return sub(num1, num2);
    }

    public static void main(String[] args) {
        String num1 = "48";
        String num2 = "2x";
        Sub36 sub36 = new Sub36();
        System.out.println(sub36.subString(num1, num2));
    }
}
支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者!