算法
1、单例模式,手写双重检验单例模式 懒汉式,DCL(8)
饿汉式:
public class Singleton{
private static Singleton singleton = new Singleton();
private Singleton(){}
public static Singleton getSingleton(){
return singleton;
}
}
懒汉式(线程不安全):
public class Singleton{
private static Singleton singleton = null;
private Singleton(){}
public static Singleton getSingleton(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
双重校验单例模式(DCL):
public class Singleton{
private volatile static Singleton singleton;
private Singleton(){}
public static Singleton getSingleton(){
if(singleton == null){
//类对象加锁
synchronized (Singleton.class) {
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
2、rand4生成rand6
- 给定一个 0-4随机数生成器 如何生成0-6随机数
这个题的难点在于如何保证数字出现的概率都是相等的。
0-6通过对7取余可以得到,那么就想办法凑对7取余的场景。
public class Frequency {
public static int rand7(){
while(true){
int num=5*rand5()+rand5();//0-24
if(num<21)
return num % 7;
}
}
}
//变形:如果用0-6随机生成器生成0-9随机数
public class Frequency {
public static int rand10(){
while(true){
int num=7*rand7()+rand7();
if(num<41)
//排除41-48,因为他们不能生成9,会造成各个数字出现的概率不同
return num % 10;
}
}
}
3、最长不含重复字符的子字符串(剑指offer48题)
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
双指针+哈希表 时间复杂度O(N) 空间复杂度O(1):字符的 ASCII 码范围为 0 ~ 127 ,
哈希表 dicdic 最多使用 O(128) = O(1)大小的额外空间。
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> dic = new HashMap<>();
int i = -1, res = 0;
for(int j = 0; j < s.length(); j++) {
if(dic.containsKey(s.charAt(j)))
i = Math.max(i, dic.get(s.charAt(j))); // 更新左指针 i
dic.put(s.charAt(j), j); // 哈希表记录
res = Math.max(res, j - i); // 更新结果
}
return res;
}
}
4、三个线程循环打印ABC
本题有多种方法实现,如wait,notify,synchronized等,这里给出基于Lock的实现
//使用Lock
public class ABCPrint{
private static int state = 0;
public static void main(String[] args) {
final Lock lock = new ReentrantLock();
Thread A = new Thread(new Runnable() { <a href="/profile/992988" data-card-uid="992988" class="js-nc-card" target="_blank">@Override public void run() {
while (state <= 30) {
lock.lock();
try {
if (state % 3 == 0) {
System.out.print("A");
state++;
}
} finally {
lock.unlock();
}
}
}
});
Thread B = new Thread(new Runnable() { </a><a href="/profile/992988" data-card-uid="992988" class="js-nc-card" target="_blank">@Override public void run() {
while (state <= 30) {
lock.lock();
try {
if (state % 3 == 1) {
System.out.print("B");
state++;
}
} finally {
lock.unlock();
}
}
}
});
Thread C = new Thread(new Runnable() { </a><a href="/profile/992988" data-card-uid="992988" class="js-nc-card" target="_blank">@Override public void run() {
while (state <= 30) {
lock.lock();
try {
if (state % 3 == 2) {
System.out.println("C");
state++;
}
} finally {
lock.unlock();
}
}
}
});
A.start();
B.start();
C.start();
}
}</a>
2、rand4生成rand6
[2,Rand4 shēngchéng rand6]
2, rand4 generated rand6