【学习笔记】重要代码

二分查找

public static int BinarySearch(int []array, int a) {
        int low = 0;
        int high = array.length - 1;
        int mid;
        while(low <= high) {
            mid = (low + high) / 2;   // 中间位置
            if(array[mid] == a) {
                return mid + 1;
            } else if(array[mid] < a) {   // 向右查找
                low = mid + 1;
            } else {   // 向左查找
                high = mid - 1;
            }
        }
        return -1;
}

冒泡排序

public static void bubbleSort(int[] a, int n) {
        for(int i = 0; i <= n - 1; i++) {  // 表示n次排序过程
            for(int j = 1; j < n - i; j++) {
                if(a[j - 1] > a[j]) {  // 前面的数字大于后面的数字就交换
                    // 交换a[j - 1]和a[j]
                    int temp;
                    temp = a[j - 1];
                    a[j - 1] = a[j];
                    a[j] = temp;
                }
            }
        }
        for(int i = 0; i <= n - 1; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
}

快速排序

public static void QuickSort(int[] a,int low,int high) {
        int start = low;
        int end = high;
        int key = a[low];
        while(end > start){
            //从后往前比较
            while(end > start && a[end] >= key)
                //如果没有比关键值小的,比较下一个,直到有比关键值小的交换位置,然后又从前往后比较
                end--;
            if(a[end] <= key){
                int temp = a[end];
                a[end] = a[start];
                a[start] = temp;
            }

            //从前往后比较
            while(end > start && a[start] <= key)
                //如果没有比关键值大的,比较下一个,直到有比关键值大的交换位置
                start++;
            if(a[start] >= key){
                int temp = a[start];
                a[start] = a[end];
                a[end] = temp;
            }
            // 此时第一次循环比较结束,关键值的位置已经确定了。
            // 左边的值都比关键值小,右边的值都比关键值大,但是两边的顺序还有可能是不一样的,进行下面的递归调用
        }
        //递归
        if(start > low) QuickSort(a,low,start-1);   // 左边序列。第一个索引位置到关键值索引-1
        if(end < high) QuickSort(a,end+1,high);      // 右边序列。从关键值索引+1 到最后一个
    }

单例模式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;
    }
}

dubbo接口测试

@RequestMapping(value="/testDubbo")
    publicObject testDubbo(@RequestBody JSONObject jsonObject) {
        ApplicationConfig application =new ApplicationConfig(jsonObject.getString("applicationName"));
        RegistryConfig registryConfig =newRegistryConfig();
        registryConfig.setAddress(jsonObject.getString("address"));
        application.setRegistry(registryConfig);

        ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
        reference.setApplication(application);
        reference.setInterface(jsonObject.getString("interfaceName"));
        reference.setGroup(jsonObject.getString("group"));
        reference.setTimeout(jsonObject.getInteger("timeOut"));
        reference.setGeneric(jsonObject.getBoolean("generic"));
        GenericService genericService = reference.get();
        return genericService.$invoke(jsonObject.getString("methodName"),newString[]{jsonObject.getString("parameterType")},newObject[]{jsonObject.get("parameter")});
    }

easyExcel操作excel

public void downloadExcel(JSONObject jsonObject, HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
 
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + FILE_NAME + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SearchResultItem.class)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("Sheet1")
                    .doWrite(searchResultMapper.queryByDate(jsonObject));
        } catch (Exception e) {
            response.reset();
        }
    }

集合排序

strategyPayload.getItems()
               .sort((Comparator.comparing(item -> Double.parseDouble(((StrategyPayload.Item) item).getProperties().get("similar")))
                       .thenComparing(item -> StringUtils.isBlank(((StrategyPayload.Item) item).getProperties().get("certification_information")) ?0:1)
                       .thenComparing(item -> {
                           String num = ((StrategyPayload.Item) item).getProperties().get("fans_number");
                           if(StringUtils.isBlank(num)) {
                               return0L;
                           }
                           returnLong.valueOf(num);
                       })).reversed());

字符串截取

inti = stockCode.indexOf("-");
String codePrefix = stockCode.substring(0, i);
String codeSuffix = stockCode.substring(codePrefix.length() +1);

spring boot 的yml配置文件定义list集合

pin-tire-default:
  jbplist:
    - repayment: 3
      period: 30
      imp_days_threshold: 2
      adjust_num_switch: true
      adjust_num: 1.0
    - repayment: 4
      period: 30
      imp_days_threshold: 3
      adjust_num_switch: true
      adjust_num: 1.0
@Data
@Configuration
@ConfigurationProperties(prefix = "pin-tire-default")
public class PinTireAdjustConfig {
    private List<PinTireAdjust> jbplist;

    public PinTireAdjust getDefaultConfig(String repayment) {
        return jbplist.stream()
                .filter(item -> StringUtils.equals(item.getRepayment(), repayment))
                .findFirst()
                .orElse(null);
    }

}
@Data
public class PinTireAdjust {

    private String repayment;
    private String period;
    private Integer imp_days_threshold;
    private Boolean adjust_num_switch;
    private Double adjust_num;
}

二进制输出

for(int i = 31; i >= 0; i--) {
    System.out.print((num & ( 1 << i )) == 0 ? "0" : "1");
}

单链表反转

public static Node reverseLinkedList(Node head) {
    Node pre = null;
    Node next = null;
    while (head != null) {
        next = head.next;
        head.next = pre;
        pre = head;
        head = next;
    }
    return pre;
}

双链表反转

public static DoubleNode reverseDoubleList(DoubleNode head) {
    DoubleNode pre = null;
    DoubleNode next = null;
    while (head != null) {
        next = head.next;
        head.next = pre;
        head.last = next;
        pre = head;
        head = next;
    }
    return pre;
}

堆排序

public class HeapSort {

    // 调整堆结构
    private static void adjustHeap(int[] arr, int i, int len) {
        int temp = arr[i];
        for (int k = 2 * i + 1; k < len; k = k * 2 + 1) {
            if (k + 1 < len && arr[k] < arr[k + 1]) {
                k++;
            }
            if (arr[k] > temp) {
                arr[i] = arr[k];
                i = k;
            } else {
                break;
            }
        }
        arr[i] = temp;
    }

    // 建堆
    private static void buildHeap(int[] arr) {
        int len = arr.length;
        // 从最后一个非叶子节点开始调整堆
        for (int i = len / 2 - 1; i >= 0; i--) {
            adjustHeap(arr, i, len);
        }
    }

    // 堆排序
    public static void heapSort(int[] arr) {
        // 建堆
        buildHeap(arr);
        // 依次将堆顶元素与末尾元素交换,并调整堆结构
        for (int i = arr.length - 1; i > 0; i--) {
            swap(arr, 0, i);
            adjustHeap(arr, 0, i);
        }
    }

    // 交换数组中两个元素的值
    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    // 测试代码
    public static void main(String[] args) {
        int[] arr = {9, 5, 1, 7, 3, 8, 2, 4, 6};
        heapSort(arr);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}

插入排序

public static void Sort(int[] s){
    for (int i=1;i< s.length;i++){//注意i不能等于数组长度,因为数组下标从零开始而不是从1.
        int temp=s[i];//存储待插入数的数值
        int j;//j必须在此声明,如果在for循环内声明,j就不能拿出for循环使用,最后一步插入就无法执行
        for (j=i-1;j>=0&&temp<s[j];j--){
            s[j+1]=s[j];//如果大于temp,往前移动一个位置
        }
        s[j+1]=temp;//将temp插入到适当位置
    }
    System.out.println(Arrays.toString(s));//输出排好序的数组
}

归并排序

public class MergeSort {   
    public static int[] mergeSort(int[] nums, int l, int h) {
        if (l == h)
            return new int[] { nums[l] };
         
        int mid = l + (h - l) / 2;
        int[] leftArr = mergeSort(nums, l, mid); //左有序数组
        int[] rightArr = mergeSort(nums, mid + 1, h); //右有序数组
        int[] newNum = new int[leftArr.length + rightArr.length]; //新有序数组
         
        int m = 0, i = 0, j = 0; 
        while (i < leftArr.length && j < rightArr.length) {
            newNum[m++] = leftArr[i] < rightArr[j] ? leftArr[i++] : rightArr[j++];
        }
        while (i < leftArr.length)
            newNum[m++] = leftArr[i++];
        while (j < rightArr.length)
            newNum[m++] = rightArr[j++];
        return newNum;
    }
    public static void main(String[] args) {
        int[] nums = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 10 };
        int[] newNums = mergeSort(nums, 0, nums.length - 1);
        for (int x : newNums) {
            System.out.println(x);
        }
    }

}

前缀树

class Trie {
    private Trie[] children;
    private boolean isEnd;

    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }
    
    public void insert(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }
    
    public boolean search(String word) {
        Trie node = searchPrefix(word);
        return node != null && node.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }

    private Trie searchPrefix(String prefix) {
        Trie node = this;
        for (int i = 0; i < prefix.length(); i++) {
            char ch = prefix.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                return null;
            }
            node = node.children[index];
        }
        return node;
    }
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/implement-trie-prefix-tree/solutions/717239/shi-xian-trie-qian-zhui-shu-by-leetcode-ti500/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

并查集

import java.util.HashMap;
import java.util.List;
import java.util.Stack;
 
public class UnionFind {
    //样本进来会包一层,叫做元素
    public static class Element<V>{
        public V value;
        public Element(V value){
            this.value=value;
        }
    }
    public static class UnionFindSet<V>{
        public HashMap<V,Element<V>> elementHashMap;
        //key 某个元素 value 该元素的父
        public HashMap<Element<V>,Element<V>> fatherMap;
        // key 某个集合的代表元素, value 该集合的大小
        public HashMap<Element<V>,Integer> sizeMap;
        public UnionFindSet(List<V> list){
            for(V value:list){
                Element<V> element=new Element<>(value);
                elementHashMap.put(value,element);
                fatherMap.put(element,element);
                sizeMap.put(element,1);
            }
        }
        public void union(V a,V b){
            if(elementHashMap.containsKey(a) && elementHashMap.containsKey(b)) {
                Element<V> headA = elementHashMap.get(a);
                Element<V> headB=elementHashMap.get(b);
                if(headA!=headB) {
                    Element<V> big = sizeMap.get(headA) > sizeMap.get(headB) ? headA : headB;
                    Element<V> small = big == headA ? headB : headA;
                    fatherMap.put(small, big);
                    sizeMap.put(big, sizeMap.get(big) + sizeMap.get(small));
                    sizeMap.remove(small);
                }
            }
        }
        public boolean isSameSet(V a,V b){
            if(elementHashMap.containsKey(a) && elementHashMap.containsKey(b)){
                return getHead(elementHashMap.get(a))==getHead(elementHashMap.get(b));
            }
            return false;
        }
        public Element<V> getHead(Element<V> e){
            Stack<Element<V>> stack=new Stack<>();
            while(e!=fatherMap.get(e)){
                stack.push(e);
                e=fatherMap.get(e);
            }
            //此时e就是头顶节点
            while(!stack.isEmpty()){
                fatherMap.put(stack.pop(),e);
            }
            return e;
        }
    }

}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
                        
原文链接:https://blog.csdn.net/yss233333/article/details/128355786

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值