From da6559ea46dbc932e4c1bcbdbd22020c37512e4d Mon Sep 17 00:00:00 2001 From: randian666 <553798608@qq.com> Date: Mon, 23 Sep 2019 15:02:49 +0800 Subject: [PATCH 01/61] Update README.md --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 89432b9..a02d168 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,6 @@ | 🍏 | 🍎 | 🍐 | 🍈 | 🥑 | 🥔| 🍠 | 🥝 | 🍱 | 🥞 |🌽| 🥦 | :--------: | :---------: | :---------: | :---------: | :---------: | :---------:| :---------: | :-------: | :-------:| :------:|:------:| :--------: | | [JAVA基础](#JAVA基础) | [JVM知识](#JVM知识)|[开源框架知识](#开源框架知识) | [操作系统知识](#操作系统) |[多线程与并发](#多线程与并发)|[TCP与HTTP](#TCP与HTTP)| [架构设计与分布式](#架构设计与分布式) |[数据结构与算法](#数据结构与算法)|[数据库](#数据库知识)| [消息队列](#消息队列)|[缓存](#缓存) | [搜索](#搜索) -### 求职、技术交流微信群 - ### JAVA基础 - [String,Stringbuffer,StringBuilder的区](http://www.cnblogs.com/su-feng/p/6659064.html)。 From f728b42faf930ff303615ea039356b9afccbdb03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Fri, 18 Oct 2019 14:53:16 +0800 Subject: [PATCH 02/61] =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E5=8E=8B?= =?UTF-8?q?=E7=BC=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 21 ++ .../java/com/algorithm/study/demo/Demo1.java | 31 +++ .../com/algorithm/study/demo/GZIPUtils.java | 223 ++++++++++++++++++ .../com/algorithm/study/demo/MainTest.java | 79 ------- .../algorithm/study/demo/OptionalTest.java | 22 ++ .../com/algorithm/study/demo/TestBase64.java | 65 +++++ .../com/algorithm/study/demo/ZipUtil.java | 55 +++++ .../algorithm/study/demo/guava/MainTest.java | 40 ++++ .../algorithm/study/demo/util/DateUtils.java | 44 ++++ 9 files changed, 501 insertions(+), 79 deletions(-) create mode 100644 src/main/java/com/algorithm/study/demo/Demo1.java create mode 100644 src/main/java/com/algorithm/study/demo/GZIPUtils.java delete mode 100644 src/main/java/com/algorithm/study/demo/MainTest.java create mode 100644 src/main/java/com/algorithm/study/demo/OptionalTest.java create mode 100644 src/main/java/com/algorithm/study/demo/TestBase64.java create mode 100644 src/main/java/com/algorithm/study/demo/ZipUtil.java create mode 100644 src/main/java/com/algorithm/study/demo/guava/MainTest.java create mode 100644 src/main/java/com/algorithm/study/demo/util/DateUtils.java diff --git a/pom.xml b/pom.xml index 4594050..7eca3bf 100644 --- a/pom.xml +++ b/pom.xml @@ -26,6 +26,27 @@ zookeeper 3.4.6 + + + com.github.rholder + guava-retrying + 2.0.0 + + + + com.wuyushuo + spring-mould-beyond + 1.2.6 + + + + + + + com.ly.isbase + isbase + 1.0.14 + diff --git a/src/main/java/com/algorithm/study/demo/Demo1.java b/src/main/java/com/algorithm/study/demo/Demo1.java new file mode 100644 index 0000000..be8e8a6 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/Demo1.java @@ -0,0 +1,31 @@ +package com.algorithm.study.demo; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Comparator; +import java.util.Iterator; +import java.util.TreeMap; + +/** + * @author xun2.liu + * @title: Demo1 + * @projectName algorithm-study + * @description: TODO + * @date 2019/9/24 15:59 + */ +public class Demo1 { + public static void main(String[] args) { + TreeMap pairs = new TreeMap<>(Comparator.reverseOrder()); + pairs.put(new BigDecimal("10000000000000"),"c"); + + pairs.put(new BigDecimal("1000"),"a"); + pairs.put(new BigDecimal("1000"),"d"); + pairs.put(new BigDecimal(String.valueOf(Integer.MAX_VALUE)),"b"); + + Iterator iterator = pairs.keySet().iterator(); + while(iterator.hasNext()) { + BigDecimal key = iterator.next(); + System.out.println("Key: " + key + ", Value: " + pairs.get(key)); + } + } +} diff --git a/src/main/java/com/algorithm/study/demo/GZIPUtils.java b/src/main/java/com/algorithm/study/demo/GZIPUtils.java new file mode 100644 index 0000000..29b2f75 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/GZIPUtils.java @@ -0,0 +1,223 @@ +package com.algorithm.study.demo; + + +import org.apache.commons.io.FileUtils; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.util.zip.*; + +/** + * @author xun2.liu + * @title: GZIPUtils + * @projectName algorithm-study + * @description: TODO + * @date 2019/10/17 20:50 + */ +public class GZIPUtils { + + /** + * 使用gzip进行压缩 + */ + public static String gzip(String primStr) { + if (primStr == null || primStr.length() == 0) { + return primStr; + } + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + GZIPOutputStream gzip = null; + try { + gzip = new GZIPOutputStream(out); + gzip.write(primStr.getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (gzip != null) { + try { + gzip.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + + return new sun.misc.BASE64Encoder().encode(out.toByteArray()); + } + + /** + *

Description:使用gzip进行解压缩

+ * + * @param compressedStr + * @return + */ + public static String gunzip(String compressedStr) { + if (compressedStr == null) { + return null; + } + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ByteArrayInputStream in = null; + GZIPInputStream ginzip = null; + byte[] compressed = null; + String decompressed = null; + try { + compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr); + in = new ByteArrayInputStream(compressed); + ginzip = new GZIPInputStream(in); + + byte[] buffer = new byte[1024]; + int offset = -1; + while ((offset = ginzip.read(buffer)) != -1) { + out.write(buffer, 0, offset); + } + decompressed = out.toString(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (ginzip != null) { + try { + ginzip.close(); + } catch (IOException e) { + } + } + if (in != null) { + try { + in.close(); + } catch (IOException e) { + } + } + if (out != null) { + try { + out.close(); + } catch (IOException e) { + } + } + } + + return decompressed; + } + + /** + * 使用zip进行压缩 + * + * @param str 压缩前的文本 + * @return 返回压缩后的文本 + */ + public static final String zip(String str) { + if (str == null) { + return null; + } + byte[] compressed; + ByteArrayOutputStream out = null; + ZipOutputStream zout = null; + String compressedStr = null; + try { + out = new ByteArrayOutputStream(); + zout = new ZipOutputStream(out); + zout.putNextEntry(new ZipEntry("0")); + zout.write(str.getBytes()); + zout.closeEntry(); + compressed = out.toByteArray(); + compressedStr = new sun.misc.BASE64Encoder().encodeBuffer(compressed); + } catch (IOException e) { + compressed = null; + } finally { + if (zout != null) { + try { + zout.close(); + } catch (IOException e) { + } + } + if (out != null) { + try { + out.close(); + } catch (IOException e) { + } + } + } + return compressedStr; + } + + /** + * 使用zip进行解压缩 + * + * @param compressedStr 压缩后的文本 + * @return 解压后的字符串 + */ + public static final String unzip(String compressedStr) { + if (compressedStr == null) { + return null; + } + ByteArrayOutputStream out = null; + ByteArrayInputStream in = null; + ZipInputStream zin = null; + String decompressed = null; + try { + byte[] compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr); + out = new ByteArrayOutputStream(); + in = new ByteArrayInputStream(compressed); + zin = new ZipInputStream(in); + zin.getNextEntry(); + byte[] buffer = new byte[1024]; + int offset = -1; + while ((offset = zin.read(buffer)) != -1) { + out.write(buffer, 0, offset); + } + decompressed = out.toString(); + } catch (IOException e) { + decompressed = null; + } finally { + if (zin != null) { + try { + zin.close(); + } catch (IOException e) { + } + } + if (in != null) { + try { + in.close(); + } catch (IOException e) { + } + } + if (out != null) { + try { + out.close(); + } catch (IOException e) { + } + } + } + return decompressed; + } + + public static void main(String[] args) throws IOException { + String strOld = FileUtils.readFileToString(new File("D:/123456.txt"), "utf-8"); + System.out.println("压缩前长度:"+strOld.length()); + String gzip = zip(strOld); + System.out.println("压缩后长度:"+gzip.length()); + String unzip = unzip(gzip); + FileUtils.write(new File("D:/2234567.txt"),unzip,"UTF-8"); + + int num=10000; + + long beginTime = System.currentTimeMillis(); + for (int i = 0; i < num; i++) { + zip(strOld); + } + long endTime = System.currentTimeMillis(); + System.out.println("压缩总耗时"+(endTime - beginTime)); + System.out.println("压缩平均耗时"+(endTime - beginTime) / 10000); + + long currentTimeMillis = System.currentTimeMillis(); + for (int i = 0; i < 10000; i++) { + unzip(gzip); + } + long endTimeMillis = System.currentTimeMillis(); + System.out.println("解压总耗时"+(endTimeMillis - currentTimeMillis)); + System.out.println("解压平均耗时"+(endTimeMillis - currentTimeMillis) / 10000); + + } +} diff --git a/src/main/java/com/algorithm/study/demo/MainTest.java b/src/main/java/com/algorithm/study/demo/MainTest.java deleted file mode 100644 index 619c3e9..0000000 --- a/src/main/java/com/algorithm/study/demo/MainTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.algorithm.study.demo; - -import java.io.*; -import java.text.SimpleDateFormat; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; - -/** - * @Author: liuxun - * @CreateDate: 2019/1/2 上午11:29 - * @Version: 1.0 - */ -public class MainTest { - public static void main(String[] args) { - try { - String filePath="/Users/liuxun/csv.txt"; - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); - - File file=new File(filePath); - File out=new File("/Users/liuxun/out.txt"); - createFile(out); - - BufferedReader reader=new BufferedReader(new FileReader(file)); - String temp=null; - while ((temp=reader.readLine())!=null){ - StringBuffer sb=new StringBuffer(); - //双引号内的逗号不分割 双引号外的逗号进行分割 - String[] strArr = temp.trim().split(",(?=([^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)",-1); - if (strArr.length<=5){ - System.out.println("数据格式不准确"); - continue; - } - sb.append(Integer.valueOf(strArr[0])).append("\t"); - sb.append("'"+strArr[1]+"'").append("\t"); - sb.append("'"+strArr[2]+"'").append("\t"); - sb.append(Float.valueOf(strArr[3])).append("\t").append("\t"); - sb.append(sdf1.format(sdf.parse(strArr[4]))); - System.out.println(sb.toString()); - fileChaseFW("/Users/liuxun/out.txt",sb.toString()); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * 写入TXT,追加写入 - * @param filePath - * @param content - */ - public static void fileChaseFW(String filePath, String content) { - try { - //构造函数中的第二个参数true表示以追加形式写文件 - FileWriter fw = new FileWriter(filePath,true); - fw.write(content+"\n"); - fw.close(); - } catch (Exception e) { - System.out.println("文件写入失败!" + e); - } - } - /** - * 创建文件 - * @param fileName - * @return - */ - public static boolean createFile(File fileName)throws Exception{ - try{ - if(!fileName.exists()){ - fileName.createNewFile(); - } - }catch(Exception e){ - e.printStackTrace(); - } - return true; - } - - -} diff --git a/src/main/java/com/algorithm/study/demo/OptionalTest.java b/src/main/java/com/algorithm/study/demo/OptionalTest.java new file mode 100644 index 0000000..cfb1cac --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/OptionalTest.java @@ -0,0 +1,22 @@ +package com.algorithm.study.demo; + +import com.algorithm.study.demo.string.TestString; + +import java.math.BigDecimal; +import java.text.NumberFormat; +import java.util.Optional; + +/** + * @author xun2.liu + * @title: OptionalTest + * @projectName algorithm-study + * @description: TODO + * @date 2019/8/21 10:10 + */ +public class OptionalTest { + public static void main(String[] args) { + for (int i = 5; i > 0; i--) { + System.out.println(i); + } + } +} diff --git a/src/main/java/com/algorithm/study/demo/TestBase64.java b/src/main/java/com/algorithm/study/demo/TestBase64.java new file mode 100644 index 0000000..de531ed --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/TestBase64.java @@ -0,0 +1,65 @@ +package com.algorithm.study.demo; + +import com.alibaba.fastjson.JSON; +import com.ly.ie.common.utils.HessianUtils; +import com.ly.isbase.util.Base64Util; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.FileUtils; + +import java.io.File; + +/** + * @author xun2.liu + * @title: TestBase64 + * @projectName algorithm-study + * @description: TODO + * @date 2019/10/18 11:37 + */ +public class TestBase64 { + + /** + * BASE64解密 + * @throws Exception + */ + public static Object decryptBASE64(String key) throws Exception { + return HessianUtils.fromBytes(Base64Util.decode(key)); + } + /** + * BASE64加密 + */ + public static String encryptBASE64(String key) throws Exception { + return Base64Util.encodeToString(HessianUtils.toBytes(key)); + } + /** + * BASE64加密解密 + */ + public static void enAndDeCode(String str) throws Exception { + System.out.println("压缩前长度:"+str.length()); + String data = encryptBASE64(str); + System.out.println("压缩后长度:"+data.length()); + Object byteArray = decryptBASE64(data); + FileUtils.write(new File("D:/78910.txt"),byteArray.toString(),"UTF-8"); + + int num=10000; + + long beginTime = System.currentTimeMillis(); + for (int i = 0; i < num; i++) { + encryptBASE64(str); + } + long endTime = System.currentTimeMillis(); + System.out.println("压缩总耗时"+(endTime - beginTime)); + System.out.println("压缩平均耗时"+(endTime - beginTime) / 10000); + + long currentTimeMillis = System.currentTimeMillis(); + for (int i = 0; i < 10000; i++) { + decryptBASE64(data); + } + long endTimeMillis = System.currentTimeMillis(); + System.out.println("解压总耗时"+(endTimeMillis - currentTimeMillis)); + System.out.println("解压平均耗时"+(endTimeMillis - currentTimeMillis) / 10000); + } + public static void main(String[] args) throws Exception { + String strOld = FileUtils.readFileToString(new File("D:/123456.txt"), "utf-8"); + enAndDeCode(strOld); + } +} diff --git a/src/main/java/com/algorithm/study/demo/ZipUtil.java b/src/main/java/com/algorithm/study/demo/ZipUtil.java new file mode 100644 index 0000000..0028244 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/ZipUtil.java @@ -0,0 +1,55 @@ +package com.algorithm.study.demo; + +/** + * @author xun2.liu + * @title: ZipUtil + * @projectName algorithm-study + * @description: TODO + * @date 2019/10/18 13:39 + */ +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +// 将一个字符串按照zip方式压缩和解压缩 +public class ZipUtil { + + // 压缩 + public static String compress(String str) throws IOException { + if (str == null || str.length() == 0) { + return str; + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + GZIPOutputStream gzip = new GZIPOutputStream(out); + gzip.write(str.getBytes()); + gzip.close(); + return out.toString("ISO-8859-1"); + } + + // 解压缩 + public static String uncompress(String str) throws IOException { + if (str == null || str.length() == 0) { + return str; + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ByteArrayInputStream in = new ByteArrayInputStream(str + .getBytes("ISO-8859-1")); + GZIPInputStream gunzip = new GZIPInputStream(in); + byte[] buffer = new byte[256]; + int n; + while ((n = gunzip.read(buffer)) >= 0) { + out.write(buffer, 0, n); + } + // toString()使用平台默认编码,也可以显式的指定如toString("GBK") + return out.toString(); + } + + // 测试方法 + public static void main(String[] args) throws IOException { + System.out.println(ZipUtil.compress("中国China")); + System.out.println(ZipUtil.uncompress(ZipUtil.compress("中国China"))); + } + +} diff --git a/src/main/java/com/algorithm/study/demo/guava/MainTest.java b/src/main/java/com/algorithm/study/demo/guava/MainTest.java new file mode 100644 index 0000000..00452d6 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/guava/MainTest.java @@ -0,0 +1,40 @@ +package com.algorithm.study.demo.guava; + +import com.github.rholder.retry.*; +import com.google.common.base.Predicates; + +import java.io.*; +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + +/** + * guava 重试机制 + * @Author: liuxun + * @CreateDate: 2019/1/2 上午11:29 + * @Version: 1.0 + */ +public class MainTest { + public static void main(String[] args) { + //定义重试机制 + Retryer retryer = RetryerBuilder.newBuilder() + .retryIfException() //设置异常重试 + .retryIfResult(Predicates.equalTo(true)) //call方法返回true重试 + .withWaitStrategy(WaitStrategies.fixedWait(10, TimeUnit.SECONDS)) //设置10秒后重试 + .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build(); //设置重试次数 超过将出异常 + try { + retryer.call(() -> { + //这里写你的业务逻辑代码 + System.out.println("11111111111111111122222"); + return true; //需要重试返回true + }); + } catch (ExecutionException e) { + e.printStackTrace(); + } catch (RetryException e) { + e.printStackTrace(); + } + } +} + diff --git a/src/main/java/com/algorithm/study/demo/util/DateUtils.java b/src/main/java/com/algorithm/study/demo/util/DateUtils.java new file mode 100644 index 0000000..f4a2efd --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/util/DateUtils.java @@ -0,0 +1,44 @@ +package com.algorithm.study.demo.util; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * @author xun2.liu + * @title: DateUtils + * @projectName algorithm-study + * @description: TODO + * @date 2019/8/30 11:14 + */ +public class DateUtils { + private static final String formatStr = "HH:mm"; + public static void main(String args[]) throws ParseException { + String tS = "11:00"; + String tE = "12:10"; + System.out.println(getLong(tS)); + System.out.println(getLong(tE)); + System.out.println(getCurrentTime()); + System.out.println(isInZone(getLong(tS),getLong(tE),getCurrentTime())); + if(isInZone(getLong(tS),getLong(tE),getCurrentTime())){ + System.out.println("当前时间在范围中"); + }else{ + System.out.println("当前时间不在范围中"); + } + } + + private static boolean isInZone(long tStart,long tEnd,long t) throws ParseException { + return t>=tStart && t<=tEnd; + } + + private static long getLong(String timeStr) throws ParseException { + DateFormat dateFormat = new SimpleDateFormat(formatStr); + return dateFormat.parse(timeStr).getTime(); + } + + private static long getCurrentTime() throws ParseException { + DateFormat dateFormat = new SimpleDateFormat(formatStr); + return getLong(dateFormat.format(new Date())); + } +} From 69fc53f98125b0626d80327d0c0bce19fe418016 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Thu, 24 Oct 2019 14:02:42 +0800 Subject: [PATCH 03/61] =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E5=8E=8B?= =?UTF-8?q?=E7=BC=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/algorithm/study/demo/GZIPUtils.java | 34 +++--- .../algorithm/study/demo/JodaTimeUtil.java | 107 ++++++++++++++++++ .../com/algorithm/study/demo/TestDemo.java | 39 +++++++ .../com/algorithm/study/demo/util/Paging.java | 3 + 4 files changed, 166 insertions(+), 17 deletions(-) create mode 100644 src/main/java/com/algorithm/study/demo/JodaTimeUtil.java create mode 100644 src/main/java/com/algorithm/study/demo/TestDemo.java diff --git a/src/main/java/com/algorithm/study/demo/GZIPUtils.java b/src/main/java/com/algorithm/study/demo/GZIPUtils.java index 29b2f75..4438ac7 100644 --- a/src/main/java/com/algorithm/study/demo/GZIPUtils.java +++ b/src/main/java/com/algorithm/study/demo/GZIPUtils.java @@ -201,23 +201,23 @@ public static void main(String[] args) throws IOException { String unzip = unzip(gzip); FileUtils.write(new File("D:/2234567.txt"),unzip,"UTF-8"); - int num=10000; - - long beginTime = System.currentTimeMillis(); - for (int i = 0; i < num; i++) { - zip(strOld); - } - long endTime = System.currentTimeMillis(); - System.out.println("压缩总耗时"+(endTime - beginTime)); - System.out.println("压缩平均耗时"+(endTime - beginTime) / 10000); - - long currentTimeMillis = System.currentTimeMillis(); - for (int i = 0; i < 10000; i++) { - unzip(gzip); - } - long endTimeMillis = System.currentTimeMillis(); - System.out.println("解压总耗时"+(endTimeMillis - currentTimeMillis)); - System.out.println("解压平均耗时"+(endTimeMillis - currentTimeMillis) / 10000); +// int num=10000; +// +// long beginTime = System.currentTimeMillis(); +// for (int i = 0; i < num; i++) { +// zip(strOld); +// } +// long endTime = System.currentTimeMillis(); +// System.out.println("压缩总耗时"+(endTime - beginTime)); +// System.out.println("压缩平均耗时"+(endTime - beginTime) / 10000); +// +// long currentTimeMillis = System.currentTimeMillis(); +// for (int i = 0; i < 10000; i++) { +// unzip(gzip); +// } +// long endTimeMillis = System.currentTimeMillis(); +// System.out.println("解压总耗时"+(endTimeMillis - currentTimeMillis)); +// System.out.println("解压平均耗时"+(endTimeMillis - currentTimeMillis) / 10000); } } diff --git a/src/main/java/com/algorithm/study/demo/JodaTimeUtil.java b/src/main/java/com/algorithm/study/demo/JodaTimeUtil.java new file mode 100644 index 0000000..a5319f4 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/JodaTimeUtil.java @@ -0,0 +1,107 @@ +package com.algorithm.study.demo; + +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; + +import java.util.Date; + +/** + * @description: JodaTime工具类 + * @author xun2.liu + * @date 2019/5/31 11:24 + **/ +public class JodaTimeUtil { + public static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss"; + public static final String STANDARD_DAY_FORMAT = "yyyy-MM-dd"; + public static final String STANDARD_DAY_FORMAT_1 = "yyyyMMdd"; + public static final String STANDARD_MILLIS_FORMAT="yyyy-MM-dd HH:mm:ss.SSS"; + public static final String STANDARD_MINUTE_FORMAT="yyyyMMddHHmm"; + + public static Date strToDate(String dateTimeStr,String formatStr){ + DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr); + DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr); + return dateTime.toDate(); + } + public static DateTime dateToDateTime(Date date){ + DateTime dateTime = new DateTime(date); + return dateTime; + } + public static Date strToDate(String dateTimeStr){ + DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(STANDARD_FORMAT); + DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr); + return dateTime.toDate(); + } + public static Date getNow(){ + return DateTime.now().toDate(); + } + public static String getNowFormat(String formatStr){ + return DateTime.now().toString(formatStr); + } + public static String getFormatNow(){ + return DateTime.now().toString(STANDARD_DAY_FORMAT_1); + } + public static String getFormatNowDay(){ + return DateTime.now().toString(STANDARD_DAY_FORMAT); + } + + public static Long strToMillis(String dateTimeStr,String formatStr){ + DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr); + long dateTime = dateTimeFormatter.parseDateTime(dateTimeStr).getMillis(); + return dateTime; + } + + public static String dateToStr(Date date,String formatStr){ + if(date == null){ + return StringUtils.EMPTY; + } + DateTime dateTime = new DateTime(date); + return dateTime.toString(formatStr); + } + public static String dateStrToMinuteStr(String dateTimeStr,String formatStr1,String formatStr2){ + DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr1); + DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr); + return dateTime.toString(formatStr2); + } + + + + public static String dateToStr(Date date){ + if(date == null){ + return StringUtils.EMPTY; + } + DateTime dateTime = new DateTime(date); + return dateTime.toString(STANDARD_FORMAT); + } + + /** + * 解析日期 yyyy-MM-dd HH:mm:ss + * + * @param timestamp + * @return + */ + public static String format(Long timestamp, String pattern) { + String dateStr = ""; + if (null == timestamp || timestamp.longValue() < 0) { + return dateStr; + } + try { + Date date = new Date(timestamp); + dateStr=dateToStr(date,pattern); + } catch (Exception e) { + // ignore + } + return dateStr; + } + public static DateTime strToDateTime(String dateTimeStr,String formatStr){ + Date date = strToDate(dateTimeStr, formatStr); + return dateToDateTime(date); + } + + public static void main(String[] args) { + Date createTime = JodaTimeUtil.strToDate("2019-10-24 02:04:41.921", JodaTimeUtil.STANDARD_MILLIS_FORMAT); + DateTime dateTime = dateToDateTime(createTime); + System.out.println(dateTime.getHourOfDay()); + } +} diff --git a/src/main/java/com/algorithm/study/demo/TestDemo.java b/src/main/java/com/algorithm/study/demo/TestDemo.java new file mode 100644 index 0000000..74f4b59 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/TestDemo.java @@ -0,0 +1,39 @@ +package com.algorithm.study.demo; + + +import com.google.common.collect.Lists; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author xun2.liu + * @title: TestDemo + * @projectName algorithm-study + * @description: TODO + * @date 2019/10/21 17:16 + */ +public class TestDemo { + public static void main(String[] args) { +// List integers = Lists.newArrayList(1, 2, 3, 4, 5,6,7,8,9,10); +// List> partition = Lists.partition(integers, 3); +// for (List integerList : partition) { +// for (int i = 0; i < integerList.size(); i++) { +// System.out.println(integerList.get(i)); +// integerList.set(i,null); +// } +// } + + int totalNum=2000; + int pageSize=1000; + int pageNo=(totalNum+pageSize-1)/pageSize; + System.out.println(getFrom(3,1000)); + } + + public static int getFrom(int pageNo,int pageSize) { + if (pageNo<=1){ + return 0; + } + return (pageNo - 1) * pageSize; + } +} diff --git a/src/main/java/com/algorithm/study/demo/util/Paging.java b/src/main/java/com/algorithm/study/demo/util/Paging.java index c1c6427..0c96ffe 100644 --- a/src/main/java/com/algorithm/study/demo/util/Paging.java +++ b/src/main/java/com/algorithm/study/demo/util/Paging.java @@ -72,4 +72,7 @@ public int getStart() { return Math.max((page - 1) * pageSize, 0); } + public static void main(String[] args) { + + } } From 1c7830ad24d6a995c230a7319051fa3910111c5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Thu, 14 Nov 2019 17:27:09 +0800 Subject: [PATCH 04/61] =?UTF-8?q?=E9=9B=B6=E9=92=B1=E6=94=AF=E4=BB=98?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/algorithm/study/demo/GZIPUtils.java | 6 ++ .../com/algorithm/study/demo/TestDemo.java | 10 +- .../algorithm/greedyalgorithm/MoneyBusi.java | 26 +++++ .../algorithm/greedyalgorithm/Solutions.java | 99 +++++++++++++++++++ 4 files changed, 137 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/MoneyBusi.java create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/Solutions.java diff --git a/src/main/java/com/algorithm/study/demo/GZIPUtils.java b/src/main/java/com/algorithm/study/demo/GZIPUtils.java index 4438ac7..a8fe8df 100644 --- a/src/main/java/com/algorithm/study/demo/GZIPUtils.java +++ b/src/main/java/com/algorithm/study/demo/GZIPUtils.java @@ -1,12 +1,15 @@ package com.algorithm.study.demo; +import com.alibaba.fastjson.JSON; +import com.google.common.collect.Maps; import org.apache.commons.io.FileUtils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; +import java.util.Map; import java.util.zip.*; /** @@ -201,6 +204,9 @@ public static void main(String[] args) throws IOException { String unzip = unzip(gzip); FileUtils.write(new File("D:/2234567.txt"),unzip,"UTF-8"); + Map map= Maps.newHashMap(); + map.put("iflight.java.dsf.itradecore",100); + System.out.println(JSON.toJSONString(map)); // int num=10000; // // long beginTime = System.currentTimeMillis(); diff --git a/src/main/java/com/algorithm/study/demo/TestDemo.java b/src/main/java/com/algorithm/study/demo/TestDemo.java index 74f4b59..a1593f9 100644 --- a/src/main/java/com/algorithm/study/demo/TestDemo.java +++ b/src/main/java/com/algorithm/study/demo/TestDemo.java @@ -3,6 +3,7 @@ import com.google.common.collect.Lists; +import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; @@ -24,10 +25,11 @@ public static void main(String[] args) { // } // } - int totalNum=2000; - int pageSize=1000; - int pageNo=(totalNum+pageSize-1)/pageSize; - System.out.println(getFrom(3,1000)); +// int totalNum=2000; +// int pageSize=1000; +// int pageNo=(totalNum+pageSize-1)/pageSize; +// System.out.println(getFrom(3,1000)); + System.out.println(".17usoft.com".length()); } public static int getFrom(int pageNo,int pageSize) { diff --git a/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/MoneyBusi.java b/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/MoneyBusi.java new file mode 100644 index 0000000..2bd261e --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/MoneyBusi.java @@ -0,0 +1,26 @@ +package com.algorithm.study.demo.algorithm.greedyalgorithm; + +import lombok.*; + +/** + * @author xun2.liu + * @title: MoneyBusi + * @projectName algorithm-study + * @description: 零钱支付 + * @date 2019/11/14 17:19 + */ +@Getter +@Setter +@ToString +@AllArgsConstructor +@NoArgsConstructor +public class MoneyBusi { + /** 面值 */ + private String value; + + /** 张数 */ + private int num; + + /** 金额 */ + private int memory; +} diff --git a/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/Solutions.java b/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/Solutions.java new file mode 100644 index 0000000..f654d10 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/Solutions.java @@ -0,0 +1,99 @@ +package com.algorithm.study.demo.algorithm.greedyalgorithm; + +import java.util.ArrayList; +import java.util.List; +import java.util.PriorityQueue; + +/** + * @author xun2.liu + * @title: Solutions + * @projectName algorithm-study + * @description: 零钱支付问题 + * 假设我们有 1 元、2 元、5 元、10 元、20 元、50 元、100 元这些面额的纸币, + * 它们的张数分别是 c1、c2、c5、c10、c20、c50、c100。 + * 我们现在要用这些钱来支付 K 元,最少要用多少张纸币呢? + * 先用面值最大的来支付,如果不够,就继续用更小一点面值的,以此类推,最后剩下的用 1 元来补齐。 + * @date 2019/11/14 17:20 + */ +public class Solutions { + /** + * 用于存储金额的信息 + */ + private PriorityQueue moneyQueue = + new PriorityQueue<>( + (o1, o2) -> { + if (o1.getMemory() < o2.getMemory()) { + return 1; + } else if (o1.getMemory() > o2.getMemory()) { + return -1; + } + return 0; + }); + + /** + * 添加金额信息 + * @param value 面值信息 + * @param num 张数 + * @param memory 金额值 + */ + public void addMemoryInfo(String value, int num, int memory) { + moneyQueue.offer(new MoneyBusi(value, num, memory)); + } + + /** + * 计算找零钱的问题 + * + * @param money 找零的金额信息 + * @return 找零钱的信息 + */ + public List looseChange(int money) { + + List resultMemory = new ArrayList<>(); + + List moreMemory = new ArrayList<>(); + + int surplus = money; + + while (surplus > 0) { + MoneyBusi busi = moneyQueue.peek(); + + if (null != busi) { + if (busi.getMemory() <= surplus) { + busi = moneyQueue.poll(); + surplus = surplus - busi.getMemory(); + + MoneyBusi busiNew = new MoneyBusi(busi.getValue(), 1, busi.getMemory()); + resultMemory.add(busiNew); + + busi.setNum(busi.getNum() - 1); + + if (busi.getNum() > 0) { + moneyQueue.offer(busi); + } + } else { + moreMemory.add(moneyQueue.poll()); + } + } else { + break; + } + } + moneyQueue.addAll(moreMemory); + return resultMemory; + } + + public static void main(String[] args) { + Solutions instance = new Solutions(); + instance.addMemoryInfo("100元", 2, 100); + instance.addMemoryInfo("50元", 2, 50); + instance.addMemoryInfo("20元", 2, 20); + instance.addMemoryInfo("10元", 2, 10); + instance.addMemoryInfo("5元", 2, 5); + instance.addMemoryInfo("2元", 2, 2); + instance.addMemoryInfo("1元", 5, 1); + + List list = instance.looseChange(332); + for (MoneyBusi busi : list) { + System.out.println(busi); + } + } +} From 5be4cb75708bf47e0ef666e30ec9df2cbce31ada Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Thu, 14 Nov 2019 20:16:04 +0800 Subject: [PATCH 05/61] =?UTF-8?q?=E9=9B=B6=E9=92=B1=E6=94=AF=E4=BB=98?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/greedyalgorithm/Solutions.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/Solutions.java b/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/Solutions.java index f654d10..ecf31a5 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/Solutions.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/Solutions.java @@ -5,7 +5,6 @@ import java.util.PriorityQueue; /** - * @author xun2.liu * @title: Solutions * @projectName algorithm-study * @description: 零钱支付问题 @@ -17,9 +16,9 @@ */ public class Solutions { /** - * 用于存储金额的信息 + * 用于存储金额的信息,根据金额从大到小排序 */ - private PriorityQueue moneyQueue = + public PriorityQueue moneyQueue = new PriorityQueue<>( (o1, o2) -> { if (o1.getMemory() < o2.getMemory()) { @@ -55,9 +54,10 @@ public List looseChange(int money) { int surplus = money; while (surplus > 0) { + //返回队列头部元素 MoneyBusi busi = moneyQueue.peek(); - if (null != busi) { + System.out.println("当前金额:"+busi.getMemory()); if (busi.getMemory() <= surplus) { busi = moneyQueue.poll(); surplus = surplus - busi.getMemory(); @@ -90,7 +90,7 @@ public static void main(String[] args) { instance.addMemoryInfo("5元", 2, 5); instance.addMemoryInfo("2元", 2, 2); instance.addMemoryInfo("1元", 5, 1); - + System.out.println(instance.moneyQueue); List list = instance.looseChange(332); for (MoneyBusi busi : list) { System.out.println(busi); From 7dbbb6fdb3b797ad52b80136a8e7be8894dffa00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Thu, 14 Nov 2019 20:17:11 +0800 Subject: [PATCH 06/61] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/algorithm/study/demo/Demo1.java | 1 - src/main/java/com/algorithm/study/demo/GZIPUtils.java | 1 - src/main/java/com/algorithm/study/demo/JodaTimeUtil.java | 1 - src/main/java/com/algorithm/study/demo/OptionalTest.java | 1 - src/main/java/com/algorithm/study/demo/TestBase64.java | 1 - src/main/java/com/algorithm/study/demo/TestDemo.java | 7 ------- src/main/java/com/algorithm/study/demo/ZipUtil.java | 1 - .../study/demo/algorithm/greedyalgorithm/MoneyBusi.java | 1 - src/main/java/com/algorithm/study/demo/util/DateUtils.java | 1 - 9 files changed, 15 deletions(-) diff --git a/src/main/java/com/algorithm/study/demo/Demo1.java b/src/main/java/com/algorithm/study/demo/Demo1.java index be8e8a6..9072486 100644 --- a/src/main/java/com/algorithm/study/demo/Demo1.java +++ b/src/main/java/com/algorithm/study/demo/Demo1.java @@ -7,7 +7,6 @@ import java.util.TreeMap; /** - * @author xun2.liu * @title: Demo1 * @projectName algorithm-study * @description: TODO diff --git a/src/main/java/com/algorithm/study/demo/GZIPUtils.java b/src/main/java/com/algorithm/study/demo/GZIPUtils.java index a8fe8df..6d6ad8a 100644 --- a/src/main/java/com/algorithm/study/demo/GZIPUtils.java +++ b/src/main/java/com/algorithm/study/demo/GZIPUtils.java @@ -13,7 +13,6 @@ import java.util.zip.*; /** - * @author xun2.liu * @title: GZIPUtils * @projectName algorithm-study * @description: TODO diff --git a/src/main/java/com/algorithm/study/demo/JodaTimeUtil.java b/src/main/java/com/algorithm/study/demo/JodaTimeUtil.java index a5319f4..94ff6bf 100644 --- a/src/main/java/com/algorithm/study/demo/JodaTimeUtil.java +++ b/src/main/java/com/algorithm/study/demo/JodaTimeUtil.java @@ -9,7 +9,6 @@ /** * @description: JodaTime工具类 - * @author xun2.liu * @date 2019/5/31 11:24 **/ public class JodaTimeUtil { diff --git a/src/main/java/com/algorithm/study/demo/OptionalTest.java b/src/main/java/com/algorithm/study/demo/OptionalTest.java index cfb1cac..7081aba 100644 --- a/src/main/java/com/algorithm/study/demo/OptionalTest.java +++ b/src/main/java/com/algorithm/study/demo/OptionalTest.java @@ -7,7 +7,6 @@ import java.util.Optional; /** - * @author xun2.liu * @title: OptionalTest * @projectName algorithm-study * @description: TODO diff --git a/src/main/java/com/algorithm/study/demo/TestBase64.java b/src/main/java/com/algorithm/study/demo/TestBase64.java index de531ed..4af2a70 100644 --- a/src/main/java/com/algorithm/study/demo/TestBase64.java +++ b/src/main/java/com/algorithm/study/demo/TestBase64.java @@ -9,7 +9,6 @@ import java.io.File; /** - * @author xun2.liu * @title: TestBase64 * @projectName algorithm-study * @description: TODO diff --git a/src/main/java/com/algorithm/study/demo/TestDemo.java b/src/main/java/com/algorithm/study/demo/TestDemo.java index a1593f9..67ab24e 100644 --- a/src/main/java/com/algorithm/study/demo/TestDemo.java +++ b/src/main/java/com/algorithm/study/demo/TestDemo.java @@ -1,14 +1,7 @@ package com.algorithm.study.demo; -import com.google.common.collect.Lists; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; - /** - * @author xun2.liu * @title: TestDemo * @projectName algorithm-study * @description: TODO diff --git a/src/main/java/com/algorithm/study/demo/ZipUtil.java b/src/main/java/com/algorithm/study/demo/ZipUtil.java index 0028244..851c4c4 100644 --- a/src/main/java/com/algorithm/study/demo/ZipUtil.java +++ b/src/main/java/com/algorithm/study/demo/ZipUtil.java @@ -1,7 +1,6 @@ package com.algorithm.study.demo; /** - * @author xun2.liu * @title: ZipUtil * @projectName algorithm-study * @description: TODO diff --git a/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/MoneyBusi.java b/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/MoneyBusi.java index 2bd261e..e402baa 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/MoneyBusi.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/MoneyBusi.java @@ -3,7 +3,6 @@ import lombok.*; /** - * @author xun2.liu * @title: MoneyBusi * @projectName algorithm-study * @description: 零钱支付 diff --git a/src/main/java/com/algorithm/study/demo/util/DateUtils.java b/src/main/java/com/algorithm/study/demo/util/DateUtils.java index f4a2efd..dbca451 100644 --- a/src/main/java/com/algorithm/study/demo/util/DateUtils.java +++ b/src/main/java/com/algorithm/study/demo/util/DateUtils.java @@ -6,7 +6,6 @@ import java.util.Date; /** - * @author xun2.liu * @title: DateUtils * @projectName algorithm-study * @description: TODO From 95e84e1e02ba68cf63317722890de0b90239e37b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Thu, 14 Nov 2019 20:21:09 +0800 Subject: [PATCH 07/61] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/algorithm/study/demo/TestDemo.java | 34 ------------------- 1 file changed, 34 deletions(-) delete mode 100644 src/main/java/com/algorithm/study/demo/TestDemo.java diff --git a/src/main/java/com/algorithm/study/demo/TestDemo.java b/src/main/java/com/algorithm/study/demo/TestDemo.java deleted file mode 100644 index 67ab24e..0000000 --- a/src/main/java/com/algorithm/study/demo/TestDemo.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.algorithm.study.demo; - - -/** - * @title: TestDemo - * @projectName algorithm-study - * @description: TODO - * @date 2019/10/21 17:16 - */ -public class TestDemo { - public static void main(String[] args) { -// List integers = Lists.newArrayList(1, 2, 3, 4, 5,6,7,8,9,10); -// List> partition = Lists.partition(integers, 3); -// for (List integerList : partition) { -// for (int i = 0; i < integerList.size(); i++) { -// System.out.println(integerList.get(i)); -// integerList.set(i,null); -// } -// } - -// int totalNum=2000; -// int pageSize=1000; -// int pageNo=(totalNum+pageSize-1)/pageSize; -// System.out.println(getFrom(3,1000)); - System.out.println(".17usoft.com".length()); - } - - public static int getFrom(int pageNo,int pageSize) { - if (pageNo<=1){ - return 0; - } - return (pageNo - 1) * pageSize; - } -} From 551145f9ef4f7a99b2c1f41b0ca69eac58da841c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Fri, 15 Nov 2019 16:23:57 +0800 Subject: [PATCH 08/61] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../study/demo/algorithm/greedyalgorithm/Solutions.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/Solutions.java b/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/Solutions.java index ecf31a5..761a235 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/Solutions.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/greedyalgorithm/Solutions.java @@ -5,6 +5,7 @@ import java.util.PriorityQueue; /** + * @author liuxun * @title: Solutions * @projectName algorithm-study * @description: 零钱支付问题 From 29deef8a6436507fda025055efab9a02b6907ad8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Tue, 19 Nov 2019 17:06:27 +0800 Subject: [PATCH 09/61] =?UTF-8?q?huffman=E7=BC=96=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../huffman/DataOutputStreamHuffman.java | 59 ++++++ .../demo/algorithm/huffman/HuffmanCode.java | 193 ++++++++++++++++++ 2 files changed, 252 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/huffman/DataOutputStreamHuffman.java create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/huffman/HuffmanCode.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/huffman/DataOutputStreamHuffman.java b/src/main/java/com/algorithm/study/demo/algorithm/huffman/DataOutputStreamHuffman.java new file mode 100644 index 0000000..1d622e4 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/huffman/DataOutputStreamHuffman.java @@ -0,0 +1,59 @@ +package com.algorithm.study.demo.algorithm.huffman; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; + +/** + * @author xun2.liu + * @title: DataOutputStreamHuffman + * @projectName algorithm-study + * @description: TODO + * @date 2019/11/19 17:03 + */ +public class DataOutputStreamHuffman { + + public static final DataOutputStreamHuffman OUTPUT = new DataOutputStreamHuffman(); + + public static final String path = "D:\\java\\test\\datastruct\\hoffman\\"; + + public void outtoFile(byte[] value) { + FileOutputStream output = null; + try { + output = new FileOutputStream(path + "src.file"); + output.write(value); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (null != output) { + try { + output.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + public void outHuffmantoFile(byte[] value) { + FileOutputStream output = null; + try { + output = new FileOutputStream(path + "out.huff"); + output.write(value); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (null != output) { + try { + output.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + +} diff --git a/src/main/java/com/algorithm/study/demo/algorithm/huffman/HuffmanCode.java b/src/main/java/com/algorithm/study/demo/algorithm/huffman/HuffmanCode.java new file mode 100644 index 0000000..9d72631 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/huffman/HuffmanCode.java @@ -0,0 +1,193 @@ +package com.algorithm.study.demo.algorithm.huffman; + +import java.util.*; +/** + * @author xun2.liu + * @title: HuffmanCode + * @projectName algorithm-study + * @description: TODO + * @date 2019/11/19 17:03 + */ +public class HuffmanCode { + /** 根节点信息,根据编码后设置根节点信息 */ + public CodeNode root; + + /** 节点信息 */ + public class CodeNode { + /** 编码存储的数据信息 */ + public char data; + + /** 字符出现的频率 */ + public int frequence; + + /** 霍夫漫编码左节点 */ + public CodeNode left; + + /** 霍夫漫编码右节点 */ + public CodeNode right; + + /** 父节点信息 */ + public CodeNode parent; + + /** 标识是否为计算添加节点 */ + public boolean addNode; + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("CodeNode{"); + sb.append("data=").append(data); + sb.append(", frequence=").append(frequence); + sb.append('}'); + return sb.toString(); + } + } + /** + * 编码,形成每个字符的霍夫漫编码 + * + * @param map 统计信息 + * @return 结果编码后的信息 + */ + public Map getHuffManCode(Map map) { + if (null != map && !map.isEmpty()) { + // 使用小顶堆来进行数据的存储 + PriorityQueue nodePriQueue = + new PriorityQueue<>( + map.size(), + (o1, o2) -> { + if (o1.frequence > o2.frequence) { + return 1; + } else if (o1.frequence < o2.frequence) { + return -1; + } + return 0; + }); + + CodeNode nodeTmp = null; + + // 1,将数据放入小顶堆中 + for (Map.Entry item : map.entrySet()) { + + nodeTmp = new CodeNode(); + nodeTmp.data = item.getKey(); + nodeTmp.frequence = item.getValue(); + + nodePriQueue.offer(nodeTmp); + } + + int queueSize = nodePriQueue.size(); + + // 将统计数据编译成霍夫漫编码树信息 + for (int i = 1; i < queueSize; i++) { + CodeNode left = nodePriQueue.poll(); + CodeNode right = nodePriQueue.poll(); + + CodeNode sumNode = new CodeNode(); + sumNode.frequence = left.frequence + right.frequence; + sumNode.data = (char) ((int) left.data + (int) right.data); + sumNode.addNode = true; + + sumNode.left = left; + sumNode.right = right; + + left.parent = sumNode; + right.parent = sumNode; + + nodePriQueue.offer(sumNode); + } + + // 构建完成 + root = nodePriQueue.poll(); + + // 构建霍夫漫编码 + Map result = this.builderCode(root); + + return result; + } + + return null; + } + + public Map builderCode(CodeNode root) { + + Map result = new HashMap<>(); + + StringBuilder code = new StringBuilder(); + + this.buildCode(code, root, result); + + return result; + } + + /** + * 进行霍夫温编码的操作,此处使用递归来实现 + * + * @param code 主串信息 + * @param node 霍夫漫编码树信息 + * @param result 存储的结果节点信息 + */ + private void buildCode(StringBuilder code, CodeNode node, Map result) { + if (null == node) { + return; + } + + if (!node.addNode) { + result.put(node.data, code.toString()); + } + + if (node.left != null) { + code.append("0"); + this.buildCode(code, node.left, result); + code.deleteCharAt(code.length() - 1); + } + + if (node.right != null) { + code.append("1"); + this.buildCode(code, node.right, result); + code.deleteCharAt(code.length() - 1); + } + } + + public String parseHuffman2(String src, Map huffman) { + StringBuilder out = new StringBuilder(); + + char[] hufSrcs = src.toCharArray(); + + for (char hufs : hufSrcs) { + out.append(huffman.get(hufs)); + } + + return out.toString(); + } + + /** + * 进行霍夫漫的解码操作 + * + * @param hufStr + * @param root + * @return + */ + public String decodeHuffman(String hufStr, CodeNode root) { + char[] hubs = hufStr.toCharArray(); + + int index = 0; + + StringBuilder resultMsg = new StringBuilder(); + + while (index < hubs.length) { + CodeNode node = root; + + do { + if (hubs[index] == '0') { + node = node.left; + } else if (hubs[index] == '1') { + node = node.right; + } + index++; + } while (index < hubs.length && (node.left != null || node.right != null)); + + resultMsg.append(node.data); + } + + return resultMsg.toString(); + } +} From 6c28c4ba8e77be9a753202eff9fcfc8aa99dfbc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Tue, 19 Nov 2019 17:08:21 +0800 Subject: [PATCH 10/61] =?UTF-8?q?huffman=E7=BC=96=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../study/demo/algorithm/huffman/StrProc.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/huffman/StrProc.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/huffman/StrProc.java b/src/main/java/com/algorithm/study/demo/algorithm/huffman/StrProc.java new file mode 100644 index 0000000..cf753bd --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/huffman/StrProc.java @@ -0,0 +1,42 @@ +package com.algorithm.study.demo.algorithm.huffman; + +import java.util.HashMap; +import java.util.Map; +/** + * @author xun2.liu + * @title: StrProc + * @projectName algorithm-study + * @description: 对字符进行统计 + * @date 2019/11/19 17:07 + */ +public class StrProc { + /** + * 对字符进行统计操作 + * + * @param str + * @return + */ + public static Map countCharset(String str) { + + if (null != str && str.length() > 0) { + + Map result = new HashMap<>(); + + char[] strChars = str.toCharArray(); + + Integer value = null; + for (int i = 0; i < strChars.length; i++) { + value = result.get(strChars[i]); + + if (value == null) { + result.put(strChars[i], 1); + } else { + result.put(strChars[i], value + 1); + } + } + + return result; + } + return null; + } +} From de24d1dc6c5cc916b775ed96f3cb6866c36f0d84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Tue, 19 Nov 2019 17:09:36 +0800 Subject: [PATCH 11/61] =?UTF-8?q?huffman=E7=BC=96=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../algorithm/huffman/TestHuffmanCode.java | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java b/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java new file mode 100644 index 0000000..fbe1fc3 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java @@ -0,0 +1,55 @@ +package com.algorithm.study.demo.algorithm.huffman; + + +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; +/** + * @author xun2.liu + * @title: TestHuffmanCode + * @projectName algorithm-study + * @description: huffman编码测试 + * @date 2019/11/19 17:08 + */ +public class TestHuffmanCode { + public static void main(String[] args) { + for (int i = 0; i < 5; i++) { + int valueRand = ThreadLocalRandom.current().nextInt(1, 50); + + StringBuilder msg = new StringBuilder(); + + for (int j = 0; j < valueRand; j++) { + msg.append((char) ThreadLocalRandom.current().nextInt(65, 122)); + } + + String src = "我我我我我我我我我我我我是是是是是是小小小小小小thisis" + msg.toString(); + + Map conMap = StrProc.countCharset(src); + + System.out.println(conMap); + + HuffmanCode instance = new HuffmanCode(); + Map huffCode = instance.getHuffManCode(conMap); + System.out.println(huffCode); + + Integer value = Integer.parseInt("1010", 2); + System.out.println(value); + + // Map parseTwo = instance.encodeHuf(huffCode); + + // String hufOutValue = instance.parseHuffman(src, parseTwo); + String hufOutValue = instance.parseHuffman2(src, huffCode); + + // DataOutputStreamHuffman.OUTPUT.outtoFile(src.getBytes(StandardCharsets.UTF_8)); + // DataOutputStreamHuffman.OUTPUT.outHuffmantoFile(hufOutValue.getBytes()); + + String deValue = instance.decodeHuffman(hufOutValue, instance.root); + System.out.println("原始" + src); + System.out.println("结果" + deValue); + +// Assert.assertEquals(src, deValue); + + System.out.println( + "--------------------------------------------------------------------------------"); + } + } +} From 555390c49e12d7bb9d1389536d59403f08c2695c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Tue, 19 Nov 2019 17:12:52 +0800 Subject: [PATCH 12/61] =?UTF-8?q?huffman=E7=BC=96=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../study/demo/algorithm/huffman/TestHuffmanCode.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java b/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java index fbe1fc3..58bae54 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java @@ -12,7 +12,7 @@ */ public class TestHuffmanCode { public static void main(String[] args) { - for (int i = 0; i < 5; i++) { +// for (int i = 0; i < 5; i++) { int valueRand = ThreadLocalRandom.current().nextInt(1, 50); StringBuilder msg = new StringBuilder(); @@ -43,13 +43,13 @@ public static void main(String[] args) { // DataOutputStreamHuffman.OUTPUT.outHuffmantoFile(hufOutValue.getBytes()); String deValue = instance.decodeHuffman(hufOutValue, instance.root); - System.out.println("原始" + src); - System.out.println("结果" + deValue); + System.out.println("原始:" + src); + System.out.println("结果:" + deValue); // Assert.assertEquals(src, deValue); System.out.println( "--------------------------------------------------------------------------------"); } - } +// } } From f8b863e39fe1b518f5c67810c2801bc89924336e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Mon, 25 Nov 2019 00:57:38 +0800 Subject: [PATCH 13/61] =?UTF-8?q?LZ77=E7=AE=97=E6=B3=95=E7=AE=80=E5=8D=95?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/algorithm/study/demo/Demo1.java | 27 ++-- .../algorithm/huffman/TestHuffmanCode.java | 4 +- .../study/demo/algorithm/lz77/LZ77Codec.java | 123 ++++++++++++++++++ .../com/algorithm/study/demo/model/User.java | 3 +- 4 files changed, 142 insertions(+), 15 deletions(-) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/lz77/LZ77Codec.java diff --git a/src/main/java/com/algorithm/study/demo/Demo1.java b/src/main/java/com/algorithm/study/demo/Demo1.java index 9072486..1a9c4c4 100644 --- a/src/main/java/com/algorithm/study/demo/Demo1.java +++ b/src/main/java/com/algorithm/study/demo/Demo1.java @@ -1,5 +1,10 @@ package com.algorithm.study.demo; +import com.algorithm.study.demo.model.User; +import com.alibaba.fastjson.JSON; +import org.apache.commons.lang3.StringUtils; + +import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Comparator; @@ -13,18 +18,16 @@ * @date 2019/9/24 15:59 */ public class Demo1 { - public static void main(String[] args) { - TreeMap pairs = new TreeMap<>(Comparator.reverseOrder()); - pairs.put(new BigDecimal("10000000000000"),"c"); - - pairs.put(new BigDecimal("1000"),"a"); - pairs.put(new BigDecimal("1000"),"d"); - pairs.put(new BigDecimal(String.valueOf(Integer.MAX_VALUE)),"b"); + public static void main(String[] args) throws Exception { + User user=new User(); + user.setId(1); + setUserName(user,"name","刘勋"); + System.out.println(JSON.toJSONString(user)); + } - Iterator iterator = pairs.keySet().iterator(); - while(iterator.hasNext()) { - BigDecimal key = iterator.next(); - System.out.println("Key: " + key + ", Value: " + pairs.get(key)); - } + private static void setUserName(User t, String column, String name) throws Exception { + Field f = t.getClass().getDeclaredField(column); + f.setAccessible(true); + f.set(t, name); } } diff --git a/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java b/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java index 58bae54..a069bf4 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java @@ -21,7 +21,7 @@ public static void main(String[] args) { msg.append((char) ThreadLocalRandom.current().nextInt(65, 122)); } - String src = "我我我我我我我我我我我我是是是是是是小小小小小小thisis" + msg.toString(); + String src = "我我是是一只小小鸟" + msg.toString(); Map conMap = StrProc.countCharset(src); @@ -38,7 +38,7 @@ public static void main(String[] args) { // String hufOutValue = instance.parseHuffman(src, parseTwo); String hufOutValue = instance.parseHuffman2(src, huffCode); - + System.out.println(hufOutValue); // DataOutputStreamHuffman.OUTPUT.outtoFile(src.getBytes(StandardCharsets.UTF_8)); // DataOutputStreamHuffman.OUTPUT.outHuffmantoFile(hufOutValue.getBytes()); diff --git a/src/main/java/com/algorithm/study/demo/algorithm/lz77/LZ77Codec.java b/src/main/java/com/algorithm/study/demo/algorithm/lz77/LZ77Codec.java new file mode 100644 index 0000000..3a03fc4 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/lz77/LZ77Codec.java @@ -0,0 +1,123 @@ +package com.algorithm.study.demo.algorithm.lz77; + +/** + * @author xun2.liu + * @title: LZ77Codec + * @projectName algorithm-study + * @description: LZ77算法实现 + * @date 2019/11/25 0:54 + */ +public class LZ77Codec { + /** + * 搜索最大相同字符串的辅助类 + */ + private class SearchResult{ + public int off = 0; + public int length = 0; + } + + /** + * search the max matched string in the slide window; + * 可以使用KMP算法提高效率 + * @param s 需要编码的字符串 + * @param currentPosition 当前位置 + * @return + */ + private SearchResult search(String s,int currentPosition){ + SearchResult result = new SearchResult(); + for (int i = 0; i < currentPosition; i++) { + SearchResult t = new SearchResult(); + for (int j = i; j < currentPosition; j++) { + // 区别已匹配和没有匹配的情况 + if(s.charAt(currentPosition+j-i)==s.charAt(j)){ + // 已经匹配的话 length+1 + // 没有匹配的话 length=1 并计算偏移量 + if(t.length >0){ + t.length++; + }else{ + t.length=1; + // 计算偏移量 + t.off = currentPosition - j; + } + }else { + break; + } + } + if(t.length>result.length){ + result=t; + } + } + return result; + } + /** + * 编码 + * + * 目前发现的问题 + * 1. 从左往右扫描和从右往左扫描off可能不一样 + * @param s 需要编码的字符串 + * @return 已经编码的字符串 + */ + String encoding(String s) { + StringBuilder builder = new StringBuilder(); + // set current coding position pointer to the start of message + int currentPosition = 0; + while (true){ + // search the max matched string in the slide window; + SearchResult result = search(s,currentPosition); + System.out.println("result:"+result.off+" "+result.length+" "+s.substring(currentPosition,currentPosition+result.length+1)); + Character nextChar = s.charAt(currentPosition+result.length); + if(result.length!=0){ + builder.append("(").append(result.off).append(",").append(result.length).append(",").append(nextChar).append(")"); + currentPosition+=result.length+1; + }else { + builder.append("(0,0,").append(nextChar).append(")"); + currentPosition++; + } + if(currentPosition>=s.length()){ + break; + } + } + return builder.toString(); + } + + /** + * 解码 + * @param s 已经编码的字符串 + * @return 已经解码的字符串 + */ + String decoding(String s) { + StringBuilder builder = new StringBuilder(); + // 提取(off,length,next_char) + String[] arr = s.split("\\)\\("); + if (arr.length==0){ + return ""; + } + arr[0]=arr[0].substring(1,arr[0].length()); + if(arr.length>1){ + arr[arr.length-1]=arr[arr.length-1].substring(0,arr[arr.length-1].length()-1); + } + for(String it : arr){ + String[] data = it.split(","); + Integer off = Integer.valueOf(data[0]); + Integer length = Integer.valueOf(data[1]); + String nextChar = data[2]; + Integer iv = builder.length()-off; + for (int i = 0; i < length; i++) { + builder.append(builder.charAt(iv+i)); + } + builder.append(nextChar); + } + return builder.toString(); + } + + public static void main(String[] args) { + LZ77Codec codec = new LZ77Codec(); + String input = "AABCAABCCAABCE"; +// String output = "(0,0,A)(1,1,B)(0,0,C)(4,4,C)(5,4,E)"; + String code = codec.encoding(input); + System.out.println(code); + + String message = codec.decoding(code); + System.out.println(message); + } +} diff --git a/src/main/java/com/algorithm/study/demo/model/User.java b/src/main/java/com/algorithm/study/demo/model/User.java index ae11880..99395ee 100644 --- a/src/main/java/com/algorithm/study/demo/model/User.java +++ b/src/main/java/com/algorithm/study/demo/model/User.java @@ -6,7 +6,8 @@ public class User { private int id; private String name; - + public User(){ + } public User(int id,String name){ this.id=id; this.name=name; From 347c22a0db9fa09443694187cedf27e6110f62ca Mon Sep 17 00:00:00 2001 From: liuxun <553798608@qq.com> Date: Tue, 26 Nov 2019 22:23:50 +0800 Subject: [PATCH 14/61] Merge branch 'master' of /Users/lolita/gitwork/algorithm-study with conflicts. --- pom.xml | 28 +++---------------- src/main/java/com/algorithm/study/demo/A.java | 4 +++ .../study/demo/algorithm/FindProject.java | 7 ----- .../study/demo/base/AppleMobile.java | 5 ++++ .../study/demo/base/HuaweiMobile.java | 13 +++++++++ .../algorithm/study/demo/base/IPerson.java | 5 ++++ .../study/demo/base/IphoneXMobile.java | 8 ++++++ .../algorithm/study/demo/base/MainTest.java | 22 +++++++++++++++ .../com/algorithm/study/demo/base/Mobile.java | 9 ++++++ .../study/demo/base/YellowPerson.java | 8 ++++++ .../com/algorithm/study/demo/testng/Test.java | 11 ++++++++ .../study/demo/thread/ThreadTest.java | 7 +++++ 12 files changed, 96 insertions(+), 31 deletions(-) create mode 100644 src/main/java/com/algorithm/study/demo/A.java create mode 100644 src/main/java/com/algorithm/study/demo/base/AppleMobile.java create mode 100644 src/main/java/com/algorithm/study/demo/base/HuaweiMobile.java create mode 100644 src/main/java/com/algorithm/study/demo/base/IPerson.java create mode 100644 src/main/java/com/algorithm/study/demo/base/IphoneXMobile.java create mode 100644 src/main/java/com/algorithm/study/demo/base/MainTest.java create mode 100644 src/main/java/com/algorithm/study/demo/base/Mobile.java create mode 100644 src/main/java/com/algorithm/study/demo/base/YellowPerson.java create mode 100644 src/main/java/com/algorithm/study/demo/testng/Test.java create mode 100644 src/main/java/com/algorithm/study/demo/thread/ThreadTest.java diff --git a/pom.xml b/pom.xml index 7eca3bf..aff5910 100644 --- a/pom.xml +++ b/pom.xml @@ -20,32 +20,12 @@ cglib 2.2.2 - - - org.apache.zookeeper - zookeeper - 3.4.6 - - - - com.github.rholder - guava-retrying - 2.0.0 - - - - com.wuyushuo - spring-mould-beyond - 1.2.6 - - - - + - com.ly.isbase - isbase - 1.0.14 + org.testng + testng + 6.14.3 diff --git a/src/main/java/com/algorithm/study/demo/A.java b/src/main/java/com/algorithm/study/demo/A.java new file mode 100644 index 0000000..a767f73 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/A.java @@ -0,0 +1,4 @@ +package com.algorithm.study.demo; + +public class A { +} diff --git a/src/main/java/com/algorithm/study/demo/algorithm/FindProject.java b/src/main/java/com/algorithm/study/demo/algorithm/FindProject.java index b46445d..90ca547 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/FindProject.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/FindProject.java @@ -1,12 +1,5 @@ package com.algorithm.study.demo.algorithm; -import com.alibaba.fastjson.JSON; -import com.sun.deploy.util.StringUtils; - -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - /** * 查找算法 * Created by liuxun on 2017/4/25. diff --git a/src/main/java/com/algorithm/study/demo/base/AppleMobile.java b/src/main/java/com/algorithm/study/demo/base/AppleMobile.java new file mode 100644 index 0000000..47dd67b --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/base/AppleMobile.java @@ -0,0 +1,5 @@ +package com.algorithm.study.demo.base; + +public abstract class AppleMobile extends Mobile{ + +} diff --git a/src/main/java/com/algorithm/study/demo/base/HuaweiMobile.java b/src/main/java/com/algorithm/study/demo/base/HuaweiMobile.java new file mode 100644 index 0000000..c472308 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/base/HuaweiMobile.java @@ -0,0 +1,13 @@ +package com.algorithm.study.demo.base; + +public class HuaweiMobile extends Mobile{ + + @Override + public void call() { + System.out.println("huawei call"); + } + @Override + public void show(){ + System.out.println("niubi show"); + } +} diff --git a/src/main/java/com/algorithm/study/demo/base/IPerson.java b/src/main/java/com/algorithm/study/demo/base/IPerson.java new file mode 100644 index 0000000..34d7545 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/base/IPerson.java @@ -0,0 +1,5 @@ +package com.algorithm.study.demo.base; + +public interface IPerson { + void eat(); +} diff --git a/src/main/java/com/algorithm/study/demo/base/IphoneXMobile.java b/src/main/java/com/algorithm/study/demo/base/IphoneXMobile.java new file mode 100644 index 0000000..96d35fc --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/base/IphoneXMobile.java @@ -0,0 +1,8 @@ +package com.algorithm.study.demo.base; + +public class IphoneXMobile extends AppleMobile { + @Override + public void call() { + System.out.println("iphonex call"); + } +} diff --git a/src/main/java/com/algorithm/study/demo/base/MainTest.java b/src/main/java/com/algorithm/study/demo/base/MainTest.java new file mode 100644 index 0000000..e5798a7 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/base/MainTest.java @@ -0,0 +1,22 @@ +package com.algorithm.study.demo.base; + +public class MainTest { + private static final String msgg="123"; + public static void main(String[] args) { + MainTest mo=new MainTest(); + Mobile mobile=new IphoneXMobile(); + mobile.call(); + mobile.show(); + + System.out.println(mobile); + Mobile mobile2=new HuaweiMobile(); + mobile2.call(); + mobile2.show(); + + System.out.println(mobile); + + + IPerson per = new YellowPerson(); + per.eat(); + } +} diff --git a/src/main/java/com/algorithm/study/demo/base/Mobile.java b/src/main/java/com/algorithm/study/demo/base/Mobile.java new file mode 100644 index 0000000..e77aebf --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/base/Mobile.java @@ -0,0 +1,9 @@ +package com.algorithm.study.demo.base; + +public abstract class Mobile { + public abstract void call(); + + void show(){ + System.out.println("show"); + } +} diff --git a/src/main/java/com/algorithm/study/demo/base/YellowPerson.java b/src/main/java/com/algorithm/study/demo/base/YellowPerson.java new file mode 100644 index 0000000..4d6945a --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/base/YellowPerson.java @@ -0,0 +1,8 @@ +package com.algorithm.study.demo.base; + +public class YellowPerson implements IPerson { + @Override + public void eat() { + System.out.println("kuaizi eat"); + } +} diff --git a/src/main/java/com/algorithm/study/demo/testng/Test.java b/src/main/java/com/algorithm/study/demo/testng/Test.java new file mode 100644 index 0000000..2f1f84a --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/testng/Test.java @@ -0,0 +1,11 @@ +package com.algorithm.study.demo.testng; + +import com.algorithm.study.demo.thread.SleepUtils; + +public class Test { + + @org.testng.annotations.Test(threadPoolSize = 10, invocationCount = 10000) + public void testJsf(){ + System.out.println("asdklfjalskfdj"+Thread.currentThread().getName()); + } +} diff --git a/src/main/java/com/algorithm/study/demo/thread/ThreadTest.java b/src/main/java/com/algorithm/study/demo/thread/ThreadTest.java new file mode 100644 index 0000000..29aeda9 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/thread/ThreadTest.java @@ -0,0 +1,7 @@ +package com.algorithm.study.demo.thread; + +public class ThreadTest { + public static void main(String[] args) { + + } +} From e6bdc2b455c69476f4e290fb20a19d0d6df2ed9d Mon Sep 17 00:00:00 2001 From: liuxun <553798608@qq.com> Date: Tue, 26 Nov 2019 22:34:04 +0800 Subject: [PATCH 15/61] =?UTF-8?q?maven=E5=8C=85=E5=8D=87=E7=BA=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 33 ++++++++ src/main/java/com/algorithm/study/demo/A.java | 4 - .../java/com/algorithm/study/demo/Demo1.java | 29 +++---- .../com/algorithm/study/demo/TestBase64.java | 64 --------------- .../algorithm/study/demo/guava/MainTest.java | 80 +++++++++---------- 5 files changed, 82 insertions(+), 128 deletions(-) delete mode 100644 src/main/java/com/algorithm/study/demo/A.java delete mode 100644 src/main/java/com/algorithm/study/demo/TestBase64.java diff --git a/pom.xml b/pom.xml index aff5910..5496700 100644 --- a/pom.xml +++ b/pom.xml @@ -27,6 +27,39 @@ testng 6.14.3 + + + + com.google.guava + guava + 23.0 + + + + commons-io + commons-io + 2.4 + + + + org.projectlombok + lombok + 1.18.8 + provided + + + + joda-time + joda-time + 2.10.1 + + + + org.apache.commons + commons-lang3 + 3.9 + + diff --git a/src/main/java/com/algorithm/study/demo/A.java b/src/main/java/com/algorithm/study/demo/A.java deleted file mode 100644 index a767f73..0000000 --- a/src/main/java/com/algorithm/study/demo/A.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.algorithm.study.demo; - -public class A { -} diff --git a/src/main/java/com/algorithm/study/demo/Demo1.java b/src/main/java/com/algorithm/study/demo/Demo1.java index 1a9c4c4..4737374 100644 --- a/src/main/java/com/algorithm/study/demo/Demo1.java +++ b/src/main/java/com/algorithm/study/demo/Demo1.java @@ -1,16 +1,5 @@ package com.algorithm.study.demo; -import com.algorithm.study.demo.model.User; -import com.alibaba.fastjson.JSON; -import org.apache.commons.lang3.StringUtils; - -import java.lang.reflect.Field; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Comparator; -import java.util.Iterator; -import java.util.TreeMap; - /** * @title: Demo1 * @projectName algorithm-study @@ -19,15 +8,15 @@ */ public class Demo1 { public static void main(String[] args) throws Exception { - User user=new User(); - user.setId(1); - setUserName(user,"name","刘勋"); - System.out.println(JSON.toJSONString(user)); + System.out.println(StrToBinstr("a")); } - - private static void setUserName(User t, String column, String name) throws Exception { - Field f = t.getClass().getDeclaredField(column); - f.setAccessible(true); - f.set(t, name); + // 将字符串转换成二进制字符串,以空格相隔 + private static String StrToBinstr(String str) { + char[] strChar = str.toCharArray(); + String result = ""; + for (int i = 0; i < strChar.length; i++) { + result += Integer.toBinaryString(strChar[i]) + " "; + } + return result; } } diff --git a/src/main/java/com/algorithm/study/demo/TestBase64.java b/src/main/java/com/algorithm/study/demo/TestBase64.java deleted file mode 100644 index 4af2a70..0000000 --- a/src/main/java/com/algorithm/study/demo/TestBase64.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.algorithm.study.demo; - -import com.alibaba.fastjson.JSON; -import com.ly.ie.common.utils.HessianUtils; -import com.ly.isbase.util.Base64Util; -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.io.FileUtils; - -import java.io.File; - -/** - * @title: TestBase64 - * @projectName algorithm-study - * @description: TODO - * @date 2019/10/18 11:37 - */ -public class TestBase64 { - - /** - * BASE64解密 - * @throws Exception - */ - public static Object decryptBASE64(String key) throws Exception { - return HessianUtils.fromBytes(Base64Util.decode(key)); - } - /** - * BASE64加密 - */ - public static String encryptBASE64(String key) throws Exception { - return Base64Util.encodeToString(HessianUtils.toBytes(key)); - } - /** - * BASE64加密解密 - */ - public static void enAndDeCode(String str) throws Exception { - System.out.println("压缩前长度:"+str.length()); - String data = encryptBASE64(str); - System.out.println("压缩后长度:"+data.length()); - Object byteArray = decryptBASE64(data); - FileUtils.write(new File("D:/78910.txt"),byteArray.toString(),"UTF-8"); - - int num=10000; - - long beginTime = System.currentTimeMillis(); - for (int i = 0; i < num; i++) { - encryptBASE64(str); - } - long endTime = System.currentTimeMillis(); - System.out.println("压缩总耗时"+(endTime - beginTime)); - System.out.println("压缩平均耗时"+(endTime - beginTime) / 10000); - - long currentTimeMillis = System.currentTimeMillis(); - for (int i = 0; i < 10000; i++) { - decryptBASE64(data); - } - long endTimeMillis = System.currentTimeMillis(); - System.out.println("解压总耗时"+(endTimeMillis - currentTimeMillis)); - System.out.println("解压平均耗时"+(endTimeMillis - currentTimeMillis) / 10000); - } - public static void main(String[] args) throws Exception { - String strOld = FileUtils.readFileToString(new File("D:/123456.txt"), "utf-8"); - enAndDeCode(strOld); - } -} diff --git a/src/main/java/com/algorithm/study/demo/guava/MainTest.java b/src/main/java/com/algorithm/study/demo/guava/MainTest.java index 00452d6..445274e 100644 --- a/src/main/java/com/algorithm/study/demo/guava/MainTest.java +++ b/src/main/java/com/algorithm/study/demo/guava/MainTest.java @@ -1,40 +1,40 @@ -package com.algorithm.study.demo.guava; - -import com.github.rholder.retry.*; -import com.google.common.base.Predicates; - -import java.io.*; -import java.text.SimpleDateFormat; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; - -/** - * guava 重试机制 - * @Author: liuxun - * @CreateDate: 2019/1/2 上午11:29 - * @Version: 1.0 - */ -public class MainTest { - public static void main(String[] args) { - //定义重试机制 - Retryer retryer = RetryerBuilder.newBuilder() - .retryIfException() //设置异常重试 - .retryIfResult(Predicates.equalTo(true)) //call方法返回true重试 - .withWaitStrategy(WaitStrategies.fixedWait(10, TimeUnit.SECONDS)) //设置10秒后重试 - .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build(); //设置重试次数 超过将出异常 - try { - retryer.call(() -> { - //这里写你的业务逻辑代码 - System.out.println("11111111111111111122222"); - return true; //需要重试返回true - }); - } catch (ExecutionException e) { - e.printStackTrace(); - } catch (RetryException e) { - e.printStackTrace(); - } - } -} - +//package com.algorithm.study.demo.guava; +// +//import com.github.rholder.retry.*; +//import com.google.common.base.Predicates; +// +//import java.io.*; +//import java.text.SimpleDateFormat; +//import java.time.LocalDateTime; +//import java.time.format.DateTimeFormatter; +//import java.util.concurrent.ExecutionException; +//import java.util.concurrent.TimeUnit; +// +///** +// * guava 重试机制 +// * @Author: liuxun +// * @CreateDate: 2019/1/2 上午11:29 +// * @Version: 1.0 +// */ +//public class MainTest { +// public static void main(String[] args) { +// //定义重试机制 +// Retryer retryer = RetryerBuilder.newBuilder() +// .retryIfException() //设置异常重试 +// .retryIfResult(Predicates.equalTo(true)) //call方法返回true重试 +// .withWaitStrategy(WaitStrategies.fixedWait(10, TimeUnit.SECONDS)) //设置10秒后重试 +// .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build(); //设置重试次数 超过将出异常 +// try { +// retryer.call(() -> { +// //这里写你的业务逻辑代码 +// System.out.println("11111111111111111122222"); +// return true; //需要重试返回true +// }); +// } catch (ExecutionException e) { +// e.printStackTrace(); +// } catch (RetryException e) { +// e.printStackTrace(); +// } +// } +//} +// From 928e45cc6359167357dc039ce0ff8c6dda8e3025 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Wed, 27 Nov 2019 12:15:56 +0800 Subject: [PATCH 16/61] =?UTF-8?q?LZ77=E7=AE=97=E6=B3=95=E7=AE=80=E5=8D=95?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../algorithm/huffman/TestHuffmanCode.java | 28 ++++------------ .../study/demo/algorithm/lz77/LZ77Codec.java | 1 + .../study/demo/algorithm/string/Solution.java | 32 +++++++++++++++++++ 3 files changed, 40 insertions(+), 21 deletions(-) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/string/Solution.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java b/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java index a069bf4..8fe436f 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java @@ -14,42 +14,28 @@ public class TestHuffmanCode { public static void main(String[] args) { // for (int i = 0; i < 5; i++) { int valueRand = ThreadLocalRandom.current().nextInt(1, 50); - StringBuilder msg = new StringBuilder(); - for (int j = 0; j < valueRand; j++) { msg.append((char) ThreadLocalRandom.current().nextInt(65, 122)); } - String src = "我我是是一只小小鸟" + msg.toString(); + String src = "aabbcceed" + msg.toString(); + System.out.println("原始:" + src); Map conMap = StrProc.countCharset(src); - System.out.println(conMap); + System.out.println("字符频率统计:"+conMap); HuffmanCode instance = new HuffmanCode(); Map huffCode = instance.getHuffManCode(conMap); - System.out.println(huffCode); - - Integer value = Integer.parseInt("1010", 2); - System.out.println(value); + System.out.println("huffcode字符编码映射:"+huffCode); - // Map parseTwo = instance.encodeHuf(huffCode); - - // String hufOutValue = instance.parseHuffman(src, parseTwo); String hufOutValue = instance.parseHuffman2(src, huffCode); - System.out.println(hufOutValue); - // DataOutputStreamHuffman.OUTPUT.outtoFile(src.getBytes(StandardCharsets.UTF_8)); - // DataOutputStreamHuffman.OUTPUT.outHuffmantoFile(hufOutValue.getBytes()); + System.out.println("最终编码:"+hufOutValue); String deValue = instance.decodeHuffman(hufOutValue, instance.root); - System.out.println("原始:" + src); - System.out.println("结果:" + deValue); - -// Assert.assertEquals(src, deValue); + System.out.println("解压结果:" + deValue); - System.out.println( - "--------------------------------------------------------------------------------"); + System.out.println("--------------------------------------------------------------------------------"); } -// } } diff --git a/src/main/java/com/algorithm/study/demo/algorithm/lz77/LZ77Codec.java b/src/main/java/com/algorithm/study/demo/algorithm/lz77/LZ77Codec.java index 3a03fc4..7c0c777 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/lz77/LZ77Codec.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/lz77/LZ77Codec.java @@ -106,6 +106,7 @@ String decoding(String s) { builder.append(builder.charAt(iv+i)); } builder.append(nextChar); + System.out.println("decoding:"+iv+" "+ builder.toString()); } return builder.toString(); } diff --git a/src/main/java/com/algorithm/study/demo/algorithm/string/Solution.java b/src/main/java/com/algorithm/study/demo/algorithm/string/Solution.java new file mode 100644 index 0000000..ddf6ed5 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/string/Solution.java @@ -0,0 +1,32 @@ +package com.algorithm.study.demo.algorithm.string; + +import java.util.HashSet; +import java.util.Set; + +/** + * @author xun2.liu + * @title: Solution + * @projectName algorithm-study + * @description: 给定一个字符串,查找不重复字符的最长子字符串的长度。 + * @date 2019/11/27 11:15 + */ +public class Solution { + int lengthOfLongestSubstring(String s) { + int n = s.length(); + Set set = new HashSet(); + int ans = 0, i = 0, j = 0; + while (i < n && j < n) { + if (!set.contains(s.charAt(j))) { + set.add(s.charAt(j++));//如果不包含,j就自增 + ans = Math.max(ans, j - i);//j - i = 最大的不重复的长度。 + } else { + set.remove(s.charAt(i++));//如果包含,i就增,并把窗口后滑 + } + } + return ans; + } + public static void main(String[] args) { + String s = "jkklmmds"; + System.out.println(new Solution().lengthOfLongestSubstring(s)); + } +} From 5852cb40a050cf5d3f074f29c7c4f05d4a118443 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Wed, 27 Nov 2019 13:47:19 +0800 Subject: [PATCH 17/61] =?UTF-8?q?LZ77=E7=AE=97=E6=B3=95=E7=AE=80=E5=8D=95?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/algorithm/study/demo/GZIPUtils.java | 3 --- .../algorithm/study/demo/algorithm/huffman/HuffmanCode.java | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/main/java/com/algorithm/study/demo/GZIPUtils.java b/src/main/java/com/algorithm/study/demo/GZIPUtils.java index 6d6ad8a..dab43ce 100644 --- a/src/main/java/com/algorithm/study/demo/GZIPUtils.java +++ b/src/main/java/com/algorithm/study/demo/GZIPUtils.java @@ -203,9 +203,6 @@ public static void main(String[] args) throws IOException { String unzip = unzip(gzip); FileUtils.write(new File("D:/2234567.txt"),unzip,"UTF-8"); - Map map= Maps.newHashMap(); - map.put("iflight.java.dsf.itradecore",100); - System.out.println(JSON.toJSONString(map)); // int num=10000; // // long beginTime = System.currentTimeMillis(); diff --git a/src/main/java/com/algorithm/study/demo/algorithm/huffman/HuffmanCode.java b/src/main/java/com/algorithm/study/demo/algorithm/huffman/HuffmanCode.java index 9d72631..6de61a1 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/huffman/HuffmanCode.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/huffman/HuffmanCode.java @@ -5,7 +5,7 @@ * @author xun2.liu * @title: HuffmanCode * @projectName algorithm-study - * @description: TODO + * @description: Huffman编码 * @date 2019/11/19 17:03 */ public class HuffmanCode { From ab170a8fa20374c7a9409868320f9b995389fda3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Wed, 27 Nov 2019 18:48:14 +0800 Subject: [PATCH 18/61] =?UTF-8?q?huffman=E7=BC=96=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/algorithm/study/demo/Demo1.java | 6 +++++- src/main/java/com/algorithm/study/demo/GZIPUtils.java | 4 ++-- .../study/demo/algorithm/huffman/TestHuffmanCode.java | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/algorithm/study/demo/Demo1.java b/src/main/java/com/algorithm/study/demo/Demo1.java index 4737374..420a65d 100644 --- a/src/main/java/com/algorithm/study/demo/Demo1.java +++ b/src/main/java/com/algorithm/study/demo/Demo1.java @@ -1,5 +1,7 @@ package com.algorithm.study.demo; +import java.math.BigDecimal; + /** * @title: Demo1 * @projectName algorithm-study @@ -8,7 +10,9 @@ */ public class Demo1 { public static void main(String[] args) throws Exception { - System.out.println(StrToBinstr("a")); + BigDecimal b = new BigDecimal(0.115); + double d = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); + System.out.println(d); } // 将字符串转换成二进制字符串,以空格相隔 private static String StrToBinstr(String str) { diff --git a/src/main/java/com/algorithm/study/demo/GZIPUtils.java b/src/main/java/com/algorithm/study/demo/GZIPUtils.java index dab43ce..299f705 100644 --- a/src/main/java/com/algorithm/study/demo/GZIPUtils.java +++ b/src/main/java/com/algorithm/study/demo/GZIPUtils.java @@ -196,13 +196,13 @@ public static final String unzip(String compressedStr) { } public static void main(String[] args) throws IOException { - String strOld = FileUtils.readFileToString(new File("D:/123456.txt"), "utf-8"); + //78910.txt 123456.txt + String strOld = FileUtils.readFileToString(new File("D:/78910.txt"), "utf-8"); System.out.println("压缩前长度:"+strOld.length()); String gzip = zip(strOld); System.out.println("压缩后长度:"+gzip.length()); String unzip = unzip(gzip); FileUtils.write(new File("D:/2234567.txt"),unzip,"UTF-8"); - // int num=10000; // // long beginTime = System.currentTimeMillis(); diff --git a/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java b/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java index 8fe436f..af4f299 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/huffman/TestHuffmanCode.java @@ -19,7 +19,7 @@ public static void main(String[] args) { msg.append((char) ThreadLocalRandom.current().nextInt(65, 122)); } - String src = "aabbcceed" + msg.toString(); + String src = "aaaaaaabbcceed" + msg.toString(); System.out.println("原始:" + src); Map conMap = StrProc.countCharset(src); From 877771fea7d8d71c2804b893dfe1eae7380e0ca6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Tue, 7 Jan 2020 14:53:55 +0800 Subject: [PATCH 19/61] =?UTF-8?q?=E6=9E=9A=E4=B8=BE=E7=B1=BB=E8=A7=A3?= =?UTF-8?q?=E5=86=B3IF=20ESLE=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../study/demo/enums/Calculator.java | 15 +++ .../algorithm/study/demo/enums/MainTest.java | 25 +++++ .../algorithm/study/demo/enums/Operator.java | 48 ++++++++++ .../study/demo/java8/FunctionTest.java | 95 +++++++++++++++++++ 4 files changed, 183 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/enums/Calculator.java create mode 100644 src/main/java/com/algorithm/study/demo/enums/MainTest.java create mode 100644 src/main/java/com/algorithm/study/demo/enums/Operator.java create mode 100644 src/main/java/com/algorithm/study/demo/java8/FunctionTest.java diff --git a/src/main/java/com/algorithm/study/demo/enums/Calculator.java b/src/main/java/com/algorithm/study/demo/enums/Calculator.java new file mode 100644 index 0000000..2e4a0c2 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/enums/Calculator.java @@ -0,0 +1,15 @@ +package com.algorithm.study.demo.enums; + +/** + * @author xun2.liu + * @title: Calculator + * @projectName algorithm-study + * @description: TODO + * @date 2020/1/7 14:51 + */ +public class Calculator{ + + public int apply(int a, int b,Operator operator) { + return operator.apply(a,b); + } +} diff --git a/src/main/java/com/algorithm/study/demo/enums/MainTest.java b/src/main/java/com/algorithm/study/demo/enums/MainTest.java new file mode 100644 index 0000000..3bbd4ef --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/enums/MainTest.java @@ -0,0 +1,25 @@ +package com.algorithm.study.demo.enums; + +import com.algorithm.study.demo.JodaTimeUtil; +import com.alibaba.fastjson.JSON; +import com.google.common.collect.Maps; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * @author xun2.liu + * @title: MainTest + * @projectName algorithm-study + * @description: 枚举类解决IF ESLE问题 + * @date 2019/12/13 16:32 + */ +public class MainTest{ + public static void main(String[] args) throws ParseException { + Calculator calculator=new Calculator(); + int result=calculator.apply(2,4,Operator.ADD); + System.out.println(result); + } + +} diff --git a/src/main/java/com/algorithm/study/demo/enums/Operator.java b/src/main/java/com/algorithm/study/demo/enums/Operator.java new file mode 100644 index 0000000..54201b9 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/enums/Operator.java @@ -0,0 +1,48 @@ +package com.algorithm.study.demo.enums; + +/** + * @author xun2.liu + * @title: Operator + * @projectName algorithm-study + * @description: TODO + * @date 2019/12/13 16:31 + */ +public enum Operator { + + ADD { + @Override + public int apply(int a, int b) { + return a + b; + } + }, + + MULTIPLY { + @Override + public int apply(int a, int b) { + return a * b; + } + }, + + SUBTRACT { + @Override + public int apply(int a, int b) { + return a - b; + } + }, + + DIVIDE { + @Override + public int apply(int a, int b) { + return a / b; + } + }, + + MODULO { + @Override + public int apply(int a, int b) { + return a % b; + } + }; + + public abstract int apply(int a, int b); +} \ No newline at end of file diff --git a/src/main/java/com/algorithm/study/demo/java8/FunctionTest.java b/src/main/java/com/algorithm/study/demo/java8/FunctionTest.java new file mode 100644 index 0000000..1706fae --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/java8/FunctionTest.java @@ -0,0 +1,95 @@ +package com.algorithm.study.demo.java8; + +import org.testng.Assert; + +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; + +/** + * @author xun2.liu + * @title: FunctionTest + * @projectName algorithm-study + * @description: Consumer实例 + * @date 2019/12/20 15:19 + */ +public class FunctionTest { + public static void main(String[] args) { +// consumerTest(); + functionTest(); + } + + /*** + * Consumer是一个函数式编程接口; 顾名思义,Consumer的意思就是消费,即针对某个东西我们来使用它,因此它包含有一个有输入而无输出的accept接口方法; + * 除accept方法,它还包含有andThen这个方法; + */ + public static void consumerTest() { + Consumer f = System.out::println; + Consumer f2 = n -> System.out.println(n + "-F2"); + + //执行完F后再执行F2的Accept方法 + f.andThen(f2).accept("test"); + + //连续执行F的Accept方法 +// f.andThen(f).andThen(f).andThen(f).accept("test1"); + } + + /** + * Function测试 + * Function也是一个函数式编程接口;它代表的含义是“函数”,而函数经常是有输入输出的,因此它含有一个apply方法, + * 包含一个输入与一个输出;除apply方法外,它还有compose与andThen及indentity三个方法 + */ + public static void functionTest() { + Function f = s -> s++; + Function g = s -> s * 2; + + /** + * 下面表示在执行F时,先执行G,并且执行F时使用G的输出当作输入。 + * 相当于以下代码: + * Integer a = g.apply(1); + * System.out.println(f.apply(a)); + */ + System.out.println(f.compose(g).apply(1)); + + /** + * 表示执行F的Apply后使用其返回的值当作输入再执行G的Apply; + * 相当于以下代码 + * Integer a = f.apply(1); + * System.out.println(g.apply(a)); + */ + System.out.println(f.andThen(g).apply(1)); + + /** + * identity方法会返回一个不进行任何处理的Function,即输出与输入值相等; + */ + System.out.println(Function.identity().apply("a")); + } + + + + /** + * Predicate测试 + * Predicate为函数式接口,predicate的中文意思是“断定”,即判断的意思,判断某个东西是否满足某种条件; + * 因此它包含test方法,根据输入值来做逻辑判断,其结果为True或者False。 + */ + private static void predicateTest() { + Predicate p = o -> o.equals("test"); + Predicate g = o -> o.startsWith("t"); + + /** + * negate: 用于对原来的Predicate做取反处理; + * 如当调用p.test("test")为True时,调用p.negate().test("test")就会是False; + */ + Assert.assertFalse(p.negate().test("test")); + + /** + * and: 针对同一输入值,多个Predicate均返回True时返回True,否则返回False; + */ + Assert.assertTrue(p.and(g).test("test")); + + /** + * or: 针对同一输入值,多个Predicate只要有一个返回True则返回True,否则返回False + */ + Assert.assertTrue(p.or(g).test("ta")); + } +} From 283a3cf30c096c6c3f5b497f6026190e7c94e843 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Fri, 20 Mar 2020 15:50:09 +0800 Subject: [PATCH 20/61] =?UTF-8?q?=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/algorithm/study/demo/Demo1.java | 25 +++++----- .../algorithm/dynamicprogramming/demo1.java | 50 +++++++++++++++++++ .../study/demo/algorithm/leetcode/Day1.java | 24 +++++++++ 3 files changed, 87 insertions(+), 12 deletions(-) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/dynamicprogramming/demo1.java create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Day1.java diff --git a/src/main/java/com/algorithm/study/demo/Demo1.java b/src/main/java/com/algorithm/study/demo/Demo1.java index 420a65d..dcbb121 100644 --- a/src/main/java/com/algorithm/study/demo/Demo1.java +++ b/src/main/java/com/algorithm/study/demo/Demo1.java @@ -1,5 +1,7 @@ package com.algorithm.study.demo; +import org.apache.commons.lang3.StringUtils; + import java.math.BigDecimal; /** @@ -10,17 +12,16 @@ */ public class Demo1 { public static void main(String[] args) throws Exception { - BigDecimal b = new BigDecimal(0.115); - double d = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); - System.out.println(d); - } - // 将字符串转换成二进制字符串,以空格相隔 - private static String StrToBinstr(String str) { - char[] strChar = str.toCharArray(); - String result = ""; - for (int i = 0; i < strChar.length; i++) { - result += Integer.toBinaryString(strChar[i]) + " "; - } - return result; +// String str="2020-01-07 19:42:06.386 INFO [BUS_VCC_ORDER_DETAIL][common][][BJ2001071650476613943652869165056][VCC20200107173708DDPSYV]PsiDAOProxy 类 listBySerialNo 方法入参:BJ2001071650476613943652869165056"; +// String traceId="VCC20200107173708DDPSYV"; +// String p="["+traceId+"]"; +// if (str.indexOf(p)>0){ +// str=StringUtils.substring(str,str.indexOf("["+traceId+"]")+p.length()); +// } +// System.out.println(str); + String msg="asdfasdf"; + String throwable="asdfasdfasdfadaskdjfaskdjf"; + msg+=throwable; + System.out.println(msg); } } diff --git a/src/main/java/com/algorithm/study/demo/algorithm/dynamicprogramming/demo1.java b/src/main/java/com/algorithm/study/demo/algorithm/dynamicprogramming/demo1.java new file mode 100644 index 0000000..9fcb5f0 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/dynamicprogramming/demo1.java @@ -0,0 +1,50 @@ +package com.algorithm.study.demo.algorithm.dynamicprogramming; + +/** + * @author xun2.liu + * @title: demo1 + * @projectName algorithm-study + * @description: 动态规划 + * @date 2020/3/18 14:04 + */ +public class demo1 { + public static void main(String[] args) { + System.out.println(fib(10)); + System.out.println(fib2(10)); + } + + /** + * 重叠子问题,子问题个数为 O(2^n)。性能非常低。 + * @param n + * @return + */ + private static int fib(int n){ + if(n==1 || n==2){ + return 1; + } + return fib(n-1)+fib(n-2); + } + + /** + * 带备忘录的递归解法,解决重叠子问题。 + * 子问题个数为 O(n),时间复杂度是 O(n) + * @param n + * @return + */ + private static int fib2(int n){ + if(n==1 || n==2){ + return 1; + } + int[] memo=new int[n+1]; + return helper(memo,n); + } + private static int helper(int[] memo,int n){ + if(n==1 || n==2){ + return 1; + } + if (memo[n]!=0) { + return memo[n]; + } + return memo[n]=helper(memo,n-1)+helper(memo,n-2); + } +} diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Day1.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Day1.java new file mode 100644 index 0000000..4b154aa --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Day1.java @@ -0,0 +1,24 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * @author xun2.liu + * @title: Day1 + * @projectName algorithm-study + * @description: TODO + * @date 2020/1/7 15:05 + */ +public class Day1 { + public static void main(String[] args) { + System.out.println(Integer.MAX_VALUE); + } + + /*** + * 给出一个32位的有符号的整数,你需要将这个整数中每位上的数字进行反转 + * https://leetcode-cn.com/problems/reverse-integer/ + * @param x + * @return + */ + public static int reverse(int x){ + return 0; + } +} From b4e847701d348d7a313f3ab0befe4ea7a37b137a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Wed, 25 Mar 2020 11:33:27 +0800 Subject: [PATCH 21/61] =?UTF-8?q?=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92-?= =?UTF-8?q?=E6=96=90=E6=B3=A2=E9=82=A3=E5=A5=91=E6=95=B0=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../algorithm/dynamicprogramming/demo1.java | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/algorithm/study/demo/algorithm/dynamicprogramming/demo1.java b/src/main/java/com/algorithm/study/demo/algorithm/dynamicprogramming/demo1.java index 9fcb5f0..4488b09 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/dynamicprogramming/demo1.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/dynamicprogramming/demo1.java @@ -4,13 +4,15 @@ * @author xun2.liu * @title: demo1 * @projectName algorithm-study - * @description: 动态规划 + * @description: 动态规划-斐波那契数列 * @date 2020/3/18 14:04 */ public class demo1 { public static void main(String[] args) { System.out.println(fib(10)); System.out.println(fib2(10)); + System.out.println(fib3(10)); + System.out.println(fib4(10)); } /** @@ -47,4 +49,40 @@ private static int helper(int[] memo,int n){ } return memo[n]=helper(memo,n-1)+helper(memo,n-2); } + + /** + * DP table 数组的迭代解法 + * 空间复杂度降为 O(N) + *自底向上计算斐波那契数列 + * @param n + * @return + */ + private static int fib3(int n){ + int[] temp=new int[n+1]; + temp[1]=temp[2]=1; + for (int i=3;i<=n;i++){ + temp[i]=temp[i-1]+temp[i-2]; + } + return temp[n]; + } + + /** + * DP table 数组的迭代解法优化 + * 空间复杂度降为 O(1) + *自底向上计算斐波那契数列 + * @param n + * @return + */ + private static int fib4(int n){ + if (n==1 || n==2){ + return 1; + } + int prev=1;int curr=1; + for (int i=3;i<=n;i++){ + int temp=prev+curr; + prev=curr; + curr=temp; + } + return curr; + } } From c548c9f756e40fb76c469f6af496fb7f7c188882 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Mon, 11 May 2020 15:20:29 +0800 Subject: [PATCH 22/61] LRUCache --- .../demo/algorithm/leetcode/Solution.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution.java new file mode 100644 index 0000000..cb825b6 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution.java @@ -0,0 +1,43 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * @author xun2.liu + * @title: Solution + * @projectName algorithm-study + * @description: TODO + * @date 2020/5/9 14:42 + */ +public class Solution { + + /** + * 实现 int sqrt(int x) 函数。 + * 计算并返回 x 的平方根,其中 x 是非负整数。 + * + * 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 + * + * 示例 1: + * + * 输入: 4 + * 输出: 2 + * 示例 2: + * + * 输入: 8 + * 输出: 2 + * 说明: 8 的平方根是 2.82842...,由于返回类型是整数,小数部分将被舍去。 + * @param x + * @return + */ + public static int mySqrt(int x) { + if (x==0){ + return 0; + } + if (x==1){ + return 1; + } + return x/2; + } + + public static void main(String[] args) { + System.out.println(mySqrt(8)); + } +} From 183bcafbf86ce8acb427774f0320bdbda623ce75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Mon, 11 May 2020 15:21:09 +0800 Subject: [PATCH 23/61] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/datastructure/tree/LinkBinTree.java | 74 ++++++++++++------- 1 file changed, 48 insertions(+), 26 deletions(-) diff --git a/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java b/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java index 805abcc..35e2c95 100644 --- a/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java +++ b/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java @@ -1,9 +1,9 @@ package com.algorithm.study.demo.datastructure.tree; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.Queue; -import java.util.Stack; +import com.alibaba.fastjson.JSON; +import org.testng.collections.Lists; + +import java.util.*; /** * @@ -114,9 +114,13 @@ private void add(TreeNode t,int value){ } } private void add2(TreeNode t,int value){ + if(null==t.data){ + t.data=value; + return; + } TreeNode node=new TreeNode(value); TreeNode current=t; - while(current!=null){ + while(true){ TreeNode parentNode=current; if (current.data>value){ current=current.left; @@ -280,26 +284,43 @@ public void postOrderTraverse2(){ * 层级遍历 * @param t */ - public void divOrderTraverse(TreeNode t){ + public List> divOrderTraverse(TreeNode t){ if (t==null) { - return; + return new ArrayList>(); } + //初始化队列只包含一个节点 root 和层次编号 0 : level = 0。 + List> levels= new ArrayList<>(); Queue queue = new LinkedList() ; queue.add(root); + //树的层数 + int level=0; while(queue.size() != 0) { + //插入一个空列表,开始当前层的算法。 + levels.add(new ArrayList<>()); int len = queue.size(); + //计算当前层有多少个元素:等于队列的长度。 for(int i=0;i > lists = divOrderTraverse(root); + System.out.println(JSON.toJSONString(lists)); } /**区间搜索**/ private void searchSection(TreeNode t,int k1,int k2,ArrayList result){ @@ -364,9 +385,9 @@ public TreeNode findMax(){ return maxNode; } public static void main(String[] args) { - int[] ls=new int[]{30,9,8}; - LinkBinTree linkBinTree=new LinkBinTree(ls[0]); - for (int i=1;i list=new ArrayList(); // linkBinTree.searchSection(linkBinTree.getRoot(),10,20,list); // System.out.println("区间查询"+list.toString()); -// System.out.println("-------------递归遍历----------------"); -// linkBinTree.preOrderTraverse();//前序遍历 从根节点开始遍历 -// System.out.println("-----------------------------"); -// linkBinTree.inOrderTraverse();//中序遍历 从根节点开始 -// System.out.println("-----------------------------"); -// linkBinTree.postOrderTraverse();//后序遍历 -// System.out.println("-----------------------------"); -// linkBinTree.divOrderTraverse();//层次遍历 + System.out.println("-------------递归遍历----------------"); + linkBinTree.preOrderTraverse();//前序遍历 从根节点开始遍历 + System.out.println("-----------------------------"); + linkBinTree.inOrderTraverse();//中序遍历 从根节点开始 + System.out.println("-----------------------------"); + linkBinTree.postOrderTraverse();//后序遍历 + System.out.println("-----------------------------"); + linkBinTree.divOrderTraverse();//层次遍历 + // //前序遍历:根节点->左子树->右子树 // //中序遍历:左子树->根节点->右子树 // //后序遍历:左子树->右子树->根节点 // System.out.println(); // System.out.println("-------------非递归遍历----------------"); - linkBinTree.preOrderTraverse2();//前序遍历 +// linkBinTree.preOrderTraverse2();//前序遍历 // System.out.println("-----------------------------"); // linkBinTree.inOrderTraverse2();//中序遍历 // System.out.println("-----------------------------"); // linkBinTree.postOrderTraverse2();//后序遍历 //二叉查找树搜索 - TreeNode node = linkBinTree.find(9); - System.out.println(node.data); - System.out.println("最小值为:"+linkBinTree.findMin().data); +// TreeNode node = linkBinTree.find(9); +// System.out.println(node.data); +// System.out.println("最小值为:"+linkBinTree.findMin().data); } } From 914da66bedbbceab331d8f0cf46f0eabe82643ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Mon, 11 May 2020 15:21:43 +0800 Subject: [PATCH 24/61] LRU --- .../study/demo/LRUCache/LRUCache.java | 158 +++++++++++++--- .../study/demo/LRUCache/LRULinkedMap.java | 1 + .../algorithm/study/demo/LRUCache/LRUMap.java | 168 ------------------ .../study/demo/algorithm/leetcode/Day1.java | 24 --- 4 files changed, 132 insertions(+), 219 deletions(-) delete mode 100644 src/main/java/com/algorithm/study/demo/LRUCache/LRUMap.java delete mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Day1.java diff --git a/src/main/java/com/algorithm/study/demo/LRUCache/LRUCache.java b/src/main/java/com/algorithm/study/demo/LRUCache/LRUCache.java index 6234068..0fcbb70 100644 --- a/src/main/java/com/algorithm/study/demo/LRUCache/LRUCache.java +++ b/src/main/java/com/algorithm/study/demo/LRUCache/LRUCache.java @@ -1,48 +1,152 @@ package com.algorithm.study.demo.LRUCache; -import java.util.*; +import java.util.HashMap; +import java.util.Map; /** - * LinkedHashMap实现LRU缓存 + * LRU缓存链表实现思路 + * 每次写入数据时将数据放入链表头结点。 + * 使用数据时候将数据移动到头结点。 + * 缓存数量超过阈值时移除链表尾部数据。 * @Author: liuxun - * @CreateDate: 2019/2/13 上午10:24 + * @CreateDate: 2018/7/12 下午6:05 * @Version: 1.0 */ public class LRUCache { - MapCache cache; - public LRUCache(int capacity) { - this.cache = new MapCache(capacity); + class Node{ + private int key; + private int value; + private Node prev; + private Node next; + + public Node(int key,int value){ + this.key=key; + this.value=value; + } + public Node(){} + + public int getKey() { + return key; + } + + public void setKey(int key) { + this.key = key; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + } + private void moveToHead(Node node){ + remove(node); + addNode(node); } + //删除尾节点 + private Node popTail(){ + Node prevNode= tail.prev; + tail.prev=prevNode.prev; + prevNode.prev.next=tail; - public int get(int key) { - return cache.getOrDefault(key, -1); + prevNode.next=null; + prevNode.prev=null; + + size--; + return prevNode; } + //删除中间节点 + private void remove(Node node){ + Node prevNode=node.prev; + Node nextNode=node.next; - public void put(int key, int value) { - cache.put(key, value); + prevNode.next=nextNode; + nextNode.prev=prevNode; + + node.next=null; + node.prev=null; + + size--; } - public Collection> getAll() { - return new ArrayList>(cache.entrySet()); + //添加节点 + private void addNode(Node node){ + node.next=head.next; + node.prev=head; + node.next.prev=node; + head.next=node; + size++; + } + private Map cache=new HashMap(); + private int size=0; + private int capacity=0; + //头结点 + private Node head; + //尾结点 + private Node tail; + public LRUCache(int capacity) { + this.capacity=capacity; + //初始化头尾节点 + this.head=new Node(); + this.tail=new Node(); + head.next=tail; + tail.prev=head; } - class MapCache extends LinkedHashMap { - public int max; - public MapCache(int max) { - super(max, 0.75f, true); - this.max = max; + + public int get(int key) { + //从缓存获取 + Node node=cache.get(key); + if(null==node){ + return -1; } - protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > max; + //数据移到头结点 + moveToHead(node); + return node.value; + } + + public void put(int key, int value) { + Node node=cache.get(key); + if(null==node){ + node=new Node(key,value); + //写入新节点至头节点 + addNode(node); + cache.put(key,node); + //如果容量已满,删除尾节点 + if(size>capacity){ + //删除尾节点 + Node delNode=popTail(); + cache.remove(delNode.key); + } + }else{ + //数据更新并移到头结点 + node.value=value; + moveToHead(node); } + } + @Override + public String toString() { + StringBuilder sb = new StringBuilder() ; + for (Node node = head;node!=null;node=node.next){ + sb.append(node.getKey()).append(":") + .append(node.getValue()) + .append("-->"); + } + return sb.toString(); } public static void main(String[] args) { - LRUCache map = new LRUCache(2) ; - map.put(1,1); - System.out.println(map.get(4)); - for (Map.Entry e : map.getAll()){ - System.out.print(e.getKey() + " : " + e.getValue() + "\t"); - } + LRUCache lruMap=new LRUCache(2); + lruMap.put(1,1); + lruMap.put(2,2); + lruMap.get(1); + lruMap.put(3,3); + lruMap.get(2); + lruMap.put(4,4); + lruMap.get(1); + lruMap.get(3); + lruMap.get(4); + System.out.println(lruMap.toString()); } -} - +} diff --git a/src/main/java/com/algorithm/study/demo/LRUCache/LRULinkedMap.java b/src/main/java/com/algorithm/study/demo/LRUCache/LRULinkedMap.java index fab7c86..7f84245 100644 --- a/src/main/java/com/algorithm/study/demo/LRUCache/LRULinkedMap.java +++ b/src/main/java/com/algorithm/study/demo/LRUCache/LRULinkedMap.java @@ -25,6 +25,7 @@ public LRULinkedMap(int cacheSize){ * @param eldest * @return */ + @Override protected boolean removeEldestEntry(Map.Entry eldest){ return size()>CACHESIZE; } diff --git a/src/main/java/com/algorithm/study/demo/LRUCache/LRUMap.java b/src/main/java/com/algorithm/study/demo/LRUCache/LRUMap.java deleted file mode 100644 index f0363a3..0000000 --- a/src/main/java/com/algorithm/study/demo/LRUCache/LRUMap.java +++ /dev/null @@ -1,168 +0,0 @@ -package com.algorithm.study.demo.LRUCache; - -import java.util.HashMap; -import java.util.Map; - -/** - * LRU缓存链表实现思路 - * 每次写入数据时将数据放入链表头结点。 - * 使用数据时候将数据移动到头结点。 - * 缓存数量超过阈值时移除链表尾部数据。 - * @Author: liuxun - * @CreateDate: 2018/7/12 下午6:05 - * @Version: 1.0 - */ -public class LRUMap { - private final Map cacheMap = new HashMap<>(); - /** - * 最大缓存大小 - */ - private int cacheSize; - /** - * 节点大小 - */ - private int nodeCount; - /** - * 头结点 - */ - private Node header; - /** - * 尾结点 - */ - private Node tailer; - public LRUMap(int cacheSize) { - this.cacheSize = cacheSize; - this.header=null; - this.tailer=null; - } - public void put(K key, V value) { - cacheMap.put(key, value); - //双向链表中添加结点 - addNode(key, value); - } - public V get(K key){ - Node node = getNode(key); - //移动到头结点 - moveToHead(node) ; - return cacheMap.get(key); - } - private void moveToHead(Node node){ - //如果是最后的一个节点 - if (node.next == null){ - node.tail.next=null; - tailer=node.tail; - nodeCount -- ; - } - //如果是本来就是头节点 不作处理 - if (node.tail == null){ - return ; - } - //如果处于中间节点 - if (node.tail != null && node.next != null){ - //它的上一节点指向它的下一节点 也就删除当前节点 - node.tail.next=node.next; - nodeCount -- ; - } - //最后在头部增加当前节点 - //注意这里需要重新 new 一个对象,不然原本的node 还有着下面的引用,会造成内存溢出。 - node = new Node<>(node.getKey(),node.getValue()) ; - addHead(node) ; - } - /** - * 链表查询 效率较低 - * @param key - * @return - */ - private Node getNode(K key){ - for (Node node = header;node!=null;node=node.next){ - if (node.getKey().equals(key)){ - return node ; - } - } - return null ; - } - /** - * 写入头结点 - * @param key - * @param value - */ - private void addNode(K key, V value) { - Node node = new Node<>(key, value); - //容量满了删除最后一个 - if (cacheSize == nodeCount) { - //删除尾结点 - delTail(); - } - //写入头结点 - addHead(node); - } - /** - * 添加头结点 - * - * @param node - */ - private void addHead(Node node) { - if (header==null){ - tailer=node; - }else{ - header.tail=node; - node.next=header; - } - header=node; - nodeCount++; - } - private void delTail() { - //把尾结点从缓存中删除 - cacheMap.remove(tailer.getKey()); - tailer.tail.next=null; - tailer=tailer.tail; - nodeCount--; - } - private class Node { - private K key; - private V value; - Node tail; - Node next; - public Node(K key, V value) { - this.key = key; - this.value = value; - } - public Node() { - } - public K getKey() { - return key; - } - public void setKey(K key) { - this.key = key; - } - public V getValue() { - return value; - } - public void setValue(V value) { - this.value = value; - } - } - @Override - public String toString() { - StringBuilder sb = new StringBuilder() ; - for (Node node = header;node!=null;node=node.next){ - if (node.getKey()!=null){ - sb.append(node.getKey()).append(":") - .append(node.getValue()) - .append("-->"); - } - } - return sb.toString(); - } - public static void main(String[] args) { - LRUMap lruMap=new LRUMap<>(3); - lruMap.put("1","1"); - lruMap.put("2","2"); - lruMap.put("3","3"); - lruMap.get("1"); - lruMap.put("4","4"); - System.out.println(lruMap.toString()); - System.out.println(lruMap.cacheSize); - } - -} diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Day1.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Day1.java deleted file mode 100644 index 4b154aa..0000000 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Day1.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.algorithm.study.demo.algorithm.leetcode; - -/** - * @author xun2.liu - * @title: Day1 - * @projectName algorithm-study - * @description: TODO - * @date 2020/1/7 15:05 - */ -public class Day1 { - public static void main(String[] args) { - System.out.println(Integer.MAX_VALUE); - } - - /*** - * 给出一个32位的有符号的整数,你需要将这个整数中每位上的数字进行反转 - * https://leetcode-cn.com/problems/reverse-integer/ - * @param x - * @return - */ - public static int reverse(int x){ - return 0; - } -} From 7579e995e006ab76da79bae482789272a92675ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Mon, 11 May 2020 15:22:10 +0800 Subject: [PATCH 25/61] =?UTF-8?q?=E5=B7=A5=E5=85=B7=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/algorithm/study/demo/enums/MainTest.java | 6 ------ .../java/com/algorithm/study/demo/{ => util}/GZIPUtils.java | 2 +- .../com/algorithm/study/demo/{ => util}/JodaTimeUtil.java | 2 +- .../java/com/algorithm/study/demo/{ => util}/ZipUtil.java | 2 +- 4 files changed, 3 insertions(+), 9 deletions(-) rename src/main/java/com/algorithm/study/demo/{ => util}/GZIPUtils.java (99%) rename src/main/java/com/algorithm/study/demo/{ => util}/JodaTimeUtil.java (98%) rename src/main/java/com/algorithm/study/demo/{ => util}/ZipUtil.java (97%) diff --git a/src/main/java/com/algorithm/study/demo/enums/MainTest.java b/src/main/java/com/algorithm/study/demo/enums/MainTest.java index 3bbd4ef..85a7c04 100644 --- a/src/main/java/com/algorithm/study/demo/enums/MainTest.java +++ b/src/main/java/com/algorithm/study/demo/enums/MainTest.java @@ -1,12 +1,6 @@ package com.algorithm.study.demo.enums; -import com.algorithm.study.demo.JodaTimeUtil; -import com.alibaba.fastjson.JSON; -import com.google.common.collect.Maps; - import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; /** * @author xun2.liu diff --git a/src/main/java/com/algorithm/study/demo/GZIPUtils.java b/src/main/java/com/algorithm/study/demo/util/GZIPUtils.java similarity index 99% rename from src/main/java/com/algorithm/study/demo/GZIPUtils.java rename to src/main/java/com/algorithm/study/demo/util/GZIPUtils.java index 299f705..15c1fe5 100644 --- a/src/main/java/com/algorithm/study/demo/GZIPUtils.java +++ b/src/main/java/com/algorithm/study/demo/util/GZIPUtils.java @@ -1,4 +1,4 @@ -package com.algorithm.study.demo; +package com.algorithm.study.demo.util; import com.alibaba.fastjson.JSON; diff --git a/src/main/java/com/algorithm/study/demo/JodaTimeUtil.java b/src/main/java/com/algorithm/study/demo/util/JodaTimeUtil.java similarity index 98% rename from src/main/java/com/algorithm/study/demo/JodaTimeUtil.java rename to src/main/java/com/algorithm/study/demo/util/JodaTimeUtil.java index 94ff6bf..04432fc 100644 --- a/src/main/java/com/algorithm/study/demo/JodaTimeUtil.java +++ b/src/main/java/com/algorithm/study/demo/util/JodaTimeUtil.java @@ -1,4 +1,4 @@ -package com.algorithm.study.demo; +package com.algorithm.study.demo.util; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; diff --git a/src/main/java/com/algorithm/study/demo/ZipUtil.java b/src/main/java/com/algorithm/study/demo/util/ZipUtil.java similarity index 97% rename from src/main/java/com/algorithm/study/demo/ZipUtil.java rename to src/main/java/com/algorithm/study/demo/util/ZipUtil.java index 851c4c4..765e78b 100644 --- a/src/main/java/com/algorithm/study/demo/ZipUtil.java +++ b/src/main/java/com/algorithm/study/demo/util/ZipUtil.java @@ -1,4 +1,4 @@ -package com.algorithm.study.demo; +package com.algorithm.study.demo.util; /** * @title: ZipUtil From 6ca7f645eb093a3723f9d71833522a3798dcb441 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Mon, 11 May 2020 15:22:23 +0800 Subject: [PATCH 26/61] =?UTF-8?q?=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../study/demo/algorithm/dynamicprogramming/demo1.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/algorithm/study/demo/algorithm/dynamicprogramming/demo1.java b/src/main/java/com/algorithm/study/demo/algorithm/dynamicprogramming/demo1.java index 4488b09..31b98a5 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/dynamicprogramming/demo1.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/dynamicprogramming/demo1.java @@ -67,8 +67,8 @@ private static int fib3(int n){ } /** - * DP table 数组的迭代解法优化 - * 空间复杂度降为 O(1) + *DP table 数组的迭代解法优化 + *空间复杂度降为 O(1) *自底向上计算斐波那契数列 * @param n * @return From ab583727a1a6177183cb15f3ae5fc2349a9e4fb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Wed, 13 May 2020 16:50:25 +0800 Subject: [PATCH 27/61] leetcode --- .../demo/algorithm/leetcode/Solution.java | 87 +++++++++++++------ .../demo/algorithm/leetcode/Solution2.java | 58 +++++++++++++ .../demo/algorithm/leetcode/Solution3.java | 63 ++++++++++++++ 3 files changed, 181 insertions(+), 27 deletions(-) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution2.java create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution3.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution.java index cb825b6..0c30ee1 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution.java @@ -1,43 +1,76 @@ package com.algorithm.study.demo.algorithm.leetcode; +import com.algorithm.study.demo.LRUCache.LRUCache; + /** * @author xun2.liu * @title: Solution * @projectName algorithm-study - * @description: TODO + * @description: + * 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的, + * 并且它们的每个节点只能存储 一位 数字。 + * + * 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 + * + * 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 + * 示例: + * + * 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) + * 输出:7 -> 0 -> 8 + * 原因:342 + 465 = 807 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/add-two-numbers * @date 2020/5/9 14:42 */ public class Solution { + static class ListNode{ + private int val; + private ListNode next; + private ListNode(int val){ + this.val=val; + } + + } - /** - * 实现 int sqrt(int x) 函数。 - * 计算并返回 x 的平方根,其中 x 是非负整数。 - * - * 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 - * - * 示例 1: - * - * 输入: 4 - * 输出: 2 - * 示例 2: - * - * 输入: 8 - * 输出: 2 - * 说明: 8 的平方根是 2.82842...,由于返回类型是整数,小数部分将被舍去。 - * @param x - * @return - */ - public static int mySqrt(int x) { - if (x==0){ - return 0; + public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { + //返回的结果,初始化 + ListNode result=new ListNode(0); + //j结果游标 + ListNode curr=result; + //满十进1,存储进位 + int carry=0; + while(l1!=null || l2!=null){ + int p1=l1==null?0:l1.val; + int p2=l2==null?0:l2.val; + //计算当前两数相加后的值 + int sum=p1+p2+carry; + //计算相加后的值的进位 + carry=sum/10; + //存储当前相加后的值除以10的余数 + curr.next=new ListNode(sum%10); + //游标指向下个节点 + curr=curr.next; + + if (l1!=null){ + l1=l1.next; + } + if (l2!=null){ + l2=l2.next; + } } - if (x==1){ - return 1; + if (carry>0){ + curr.next=new ListNode(carry); } - return x/2; + return result.next; } - public static void main(String[] args) { - System.out.println(mySqrt(8)); + ListNode a=new ListNode(5); + ListNode b=new ListNode(5); + + ListNode result = addTwoNumbers(a, b); + for (ListNode node=result;node!=null;node=node.next){ + System.out.println(node.val); + } } } diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution2.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution2.java new file mode 100644 index 0000000..611281a --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution2.java @@ -0,0 +1,58 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author xun2.liu + * @title: Solution2 + * @projectName algorithm-study + * @description: + * 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 + * 示例 1: + * + * 输入: "abcabcbb" + * 输出: 3 + * 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters + * @date 2020/5/13 15:51 + */ +public class Solution2 { + /** + * 使用滑动窗口 + * 定义一个 map 数据结构存储 (k, v),其中 key 值为字符,value 值为字符位置 +1,加 1 表示从字符位置后一个才开始不重复 + * 我们定义不重复子串的开始位置为 start,结束位置为 end + * 随着 end 不断遍历向后,会遇到与 [start, end] 区间内字符相同的情况,此时将字符作为 key 值,获取其 value 值,并更新 start,此时 [start, end] + * 区间内不存在重复字符 + * 无论是否更新 start,都会更新其 map 数据结构和结果 ans。 + * 时间复杂度:O(n)O(n) + * @param s + * @return + */ + public static int lengthOfLongestSubstring(String s) { + //最长子串 的长度 + int resultLen=0; + //key为字符 value为end + Map map= new HashMap<>(); + //初始化起始位置和结束位置 + int start=0; + for(int end=0;end counter=new HashMap<>(); + for(int n:nums){ + counter.put(n,counter.getOrDefault(n,0)+1); + } + //使用每个数字出现的次数作为排序规则来建立初始化一个优先队列 + PriorityQueue heap=new PriorityQueue<>((n1,n2)-> counter.get(n1)-counter.get(n2)); + //把数字写入优先队列中 + for(int num:counter.keySet()){ + heap.add(num); + //如果优先队列中的元素大于前K个就删除,因为默认是升序。 + if(heap.size()>k){ + heap.poll(); + } + } + //取出前K个元素从优先队列中 + int[] result=new int[k]; + for(int i=0;i Date: Thu, 14 May 2020 19:57:01 +0800 Subject: [PATCH 28/61] =?UTF-8?q?=E4=B8=A4=E4=B8=AA=E6=95=B4=E6=95=B0?= =?UTF-8?q?=E7=9B=B8=E9=99=A4=E5=BE=97=E5=88=B0=E5=BE=AA=E7=8E=AF=E5=B0=8F?= =?UTF-8?q?=E6=95=B0=EF=BC=8C=E6=B1=82=E5=BE=AA=E7=8E=AF=E8=8A=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution4.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution4.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution4.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution4.java new file mode 100644 index 0000000..f597b07 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution4.java @@ -0,0 +1,51 @@ +package com.algorithm.study.demo.algorithm.leetcode; + + +import java.util.*; + +/** + * @author xun2.liu + * @title: Solution4 + * @projectName algorithm-study + * @description: 两个整数相除得到循环小数,求循环节 + * @date 2020/5/14 19:01 + */ +public class Solution4 { + + public static String function(int a, int b){ + //存储商和余数 + List> temp=new ArrayList<>(); + int value=0; + int remainder=0; + boolean flag=false; + while (!flag){ + value=a / b; + remainder= a%b; + for (int i=0;i integerIntegerMap = temp.get(i); + if (integerIntegerMap.containsKey(value) && integerIntegerMap.containsValue(remainder)){ + flag=true; + break; + } + } + HashMap map = new HashMap<>(); + map.put(value,remainder); + temp.add(map); + a=remainder*10; + } + StringBuilder sb=new StringBuilder(); + for (int i=1;i integerIntegerMap = temp.get(i); + integerIntegerMap.forEach((k,v)->{ + sb.append(k); + }); + + } + return sb.toString(); + } + + public static void main(String[] args) { + System.out.println(function(1,7)); + } + +} From e1254308ed092e4bec13425cff7e283d0c69906a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Mon, 18 May 2020 11:24:50 +0800 Subject: [PATCH 29/61] =?UTF-8?q?=E5=8F=8D=E8=BD=AC=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E5=8D=95=E9=93=BE=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../study/demo/algorithm/Suanfa50.java | 35 --------------- .../demo/algorithm/leetcode/Solution5.java | 43 +++++++++++++++++++ .../demo/datastructure/tree/AVLBinTree.java | 10 ----- 3 files changed, 43 insertions(+), 45 deletions(-) delete mode 100644 src/main/java/com/algorithm/study/demo/algorithm/Suanfa50.java create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution5.java delete mode 100644 src/main/java/com/algorithm/study/demo/datastructure/tree/AVLBinTree.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/Suanfa50.java b/src/main/java/com/algorithm/study/demo/algorithm/Suanfa50.java deleted file mode 100644 index 212720b..0000000 --- a/src/main/java/com/algorithm/study/demo/algorithm/Suanfa50.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.algorithm.study.demo.algorithm; - -import java.util.Arrays; -import java.util.BitSet; - -/** - * @Author: liuxun - * @CreateDate: 2018/12/7 下午1:35 - * @Version: 1.0 - */ -public class Suanfa50 { - public static void main(String[] args) { -// printMissingNumber(new int[]{1, 3, 6}, 6); - } - private static void printMissingNumber(int[] numbers, int count) { - int missingCount = count - numbers.length; - BitSet bitSet = new BitSet(count); - - for (int number : numbers) { - bitSet.set(number - 1); - } - - System.out.printf("Missing numbers in integer array %s, with total number %d is %n", - Arrays.toString(numbers), count); - int lastMissingIndex = 0; - - for (int i = 0; i < missingCount; i++) { - lastMissingIndex = bitSet.nextClearBit(lastMissingIndex); - System.out.println(++lastMissingIndex); - } - - } - - -} diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution5.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution5.java new file mode 100644 index 0000000..39e6f26 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution5.java @@ -0,0 +1,43 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * @author xun2.liu + * @title: Solution5 + * @projectName algorithm-study + * @description: 反转一个单链表。 + * 示例: + * 输入: 1->2->3->4->5->NULL + * 输出: 5->4->3->2->1->NULL + * @date 2020/5/14 20:07 + */ +public class Solution5 { + public static class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } + } + public static ListNode reverseList(ListNode head) { + //使用两个指针 + ListNode curr=head; + ListNode prev=null; + while(curr!=null){ + //临时指针。用来存储下一个节点。 + ListNode temp=curr.next; + curr.next=prev; + prev=curr; + curr=temp; + } + return prev; + } + + public static void main(String[] args) { + ListNode a=new ListNode(5); + ListNode b=new ListNode(4); + ListNode c=new ListNode(3); + a.next=b;b.next=c; + ListNode result = reverseList(a); + for (ListNode node=result;node!=null;node=node.next){ + System.out.println(node.val); + } + } +} diff --git a/src/main/java/com/algorithm/study/demo/datastructure/tree/AVLBinTree.java b/src/main/java/com/algorithm/study/demo/datastructure/tree/AVLBinTree.java deleted file mode 100644 index 87e47a4..0000000 --- a/src/main/java/com/algorithm/study/demo/datastructure/tree/AVLBinTree.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.algorithm.study.demo.datastructure.tree; - -/** - * AVL二叉搜索 - * @Author: liuxun - * @CreateDate: 2018/10/22 上午11:26 - * @Version: 1.0 - */ -public class AVLBinTree { -} From 1605b8f3e74f894c0b58e814d343da6b24a6f183 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Tue, 19 May 2020 21:06:57 +0800 Subject: [PATCH 30/61] =?UTF-8?q?=E7=8E=AF=E5=BD=A2=E9=93=BE=E8=A1=A8=20II?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution6.java | 49 +++++++++++++ .../demo/algorithm/leetcode/Solution7.java | 71 +++++++++++++++++++ 2 files changed, 120 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution6.java create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution6.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution6.java new file mode 100644 index 0000000..ebaa3a5 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution6.java @@ -0,0 +1,49 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * @author xun2.liu + * @title: Solution6 + * @projectName algorithm-study + * @description: 编写一个程序,找到两个单链表相交的起始节点。 + * 输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 + * 输出:Reference of the node with value = 8 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists + * @date 2020/5/18 19:35 + */ +public class Solution6 { + public static class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } + } + public static ListNode getIntersectionNode(ListNode headA, ListNode headB) { + //使用两个指针分别指向headA、headB + //同时遍历两个连表 + //当headA遍历完后指针指向headB,当headB遍历完后指针指向headA + //如此循环当两个指正都为Null的话代表没有相交的节点。 + //如果都两个指针对应的节点相等就返回相等的节点就是相交的节点 + ListNode p1=headA; + ListNode p2=headB; + while(p1!=p2){ + p1=p1==null?headB:p1.next; + p2=p2==null?headA:p2.next; + } + return p1; + } + + public static void main(String[] args) { + ListNode a=new ListNode(5); + ListNode b=new ListNode(4); + a.next=b; + ListNode c=new ListNode(6); + ListNode intersectionNode = getIntersectionNode(a, b); + if (null!=intersectionNode){ + System.out.println(intersectionNode.val); + }else{ + System.out.println("没有相交的节点哦"); + } + + } +} diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java new file mode 100644 index 0000000..1e08864 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java @@ -0,0 +1,71 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * @author xun2.liu + * @title: Solution7 + * @projectName algorithm-study + * @description: 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。 + * + * 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。 + * + * 说明:不允许修改给定的链表。 + * + * 示例 1: + * + * 输入:head = [1,2], pos = 0 + * 输出:tail connects to node index 0 + * 解释:链表中有一个环,其尾部连接到第一个节点。 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/linked-list-cycle-ii + * + * @date 2020/5/19 17:16 + */ +public class Solution7 { + public static class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } + } + + /** + * 快慢指针遍历连表。看是否相遇。如果相遇在判断是否是循环链表。 + * @param head + * @return + */ + public static ListNode detectCycle(ListNode head) { + if (null== head || head.next==null){ + return null; + } + ListNode p1=head; + ListNode p2=head; + while(p2!=null && p2.next!=null){ + p1=p1.next; + p2=p2.next.next; + if(p1==p2){ + break; + } + } + if (p1!=p2){ + return null; + } + p1=head; + while(p1!=p2){ + p1=p1.next; + p2=p2.next; + } + return p1; + } + public static void main(String[] args) { + ListNode a=new ListNode(5); + ListNode b=new ListNode(4); + ListNode c=new ListNode(6); + ListNode d=new ListNode(-1); + a.next=b; + b.next=c; + c.next=b; +// c.next=b; + ListNode listNode = detectCycle(a); + System.out.println(listNode==null?"":listNode.val); + } +} From 3693ece015cbb68ff5a2afd823b832eccee05808 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Tue, 19 May 2020 21:07:47 +0800 Subject: [PATCH 31/61] =?UTF-8?q?=E7=8E=AF=E5=BD=A2=E9=93=BE=E8=A1=A8=20II?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/algorithm/study/demo/algorithm/leetcode/Solution7.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java index 1e08864..6c8265c 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java @@ -46,6 +46,7 @@ public static ListNode detectCycle(ListNode head) { break; } } + //如果快慢指针没有相遇代表是无环链表 if (p1!=p2){ return null; } From 93d4ca48caa727323b75dc4dcf8c55c3d650bcfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Wed, 20 May 2020 21:32:39 +0800 Subject: [PATCH 32/61] =?UTF-8?q?=E5=88=A0=E9=99=A4=E9=93=BE=E8=A1=A8?= =?UTF-8?q?=E7=9A=84=E5=80=92=E6=95=B0=E7=AC=AC=C2=A0n=C2=A0=E4=B8=AA?= =?UTF-8?q?=E8=8A=82=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution8.java | 67 +++++++++++++++++++ .../study/demo/algorithm/string/Solution.java | 32 --------- 2 files changed, 67 insertions(+), 32 deletions(-) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution8.java delete mode 100644 src/main/java/com/algorithm/study/demo/algorithm/string/Solution.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution8.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution8.java new file mode 100644 index 0000000..e160ac7 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution8.java @@ -0,0 +1,67 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * @author xun2.liu + * @title: Solution8 + * @projectName algorithm-study + * @description: 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 + * + * 示例: + * 给定一个链表: 1->2->3->4->5, 和 n = 2. + * 当删除了倒数第二个节点后,链表变为 1->2->3->5. + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list + * @date 2020/5/20 21:01 + */ +public class Solution8 { + public static class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } + } + /** + * 我们可以使用两个指针而不是一个指针。第一个指针从列表的开头向前移动 n+1步,而第二个指针将从列表的开头出发。现在,这两个指针被n个结点分开。 + * 我们通过同时移动两个指针向前来保持这个恒定的间隔,直到第一个指针到达最后一个结点。此时第二个指针将指向从最后一个结点数起的第n个结点。 + * 我们重新链接第二个指针所引用的结点的 next 指针指向该结点的下下个结点。 + * @param head + * @param n + * @return + */ + public static ListNode removeNthFromEnd(ListNode head, int n) { + if (head.next==null){ + return null; + } + ListNode temp=new ListNode(-1); + temp.next=head; + ListNode p1=temp; + ListNode p2=temp; + //第一个指针从列表的开头向前移动 n+1步 + for (int i=0;i set = new HashSet(); - int ans = 0, i = 0, j = 0; - while (i < n && j < n) { - if (!set.contains(s.charAt(j))) { - set.add(s.charAt(j++));//如果不包含,j就自增 - ans = Math.max(ans, j - i);//j - i = 最大的不重复的长度。 - } else { - set.remove(s.charAt(i++));//如果包含,i就增,并把窗口后滑 - } - } - return ans; - } - public static void main(String[] args) { - String s = "jkklmmds"; - System.out.println(new Solution().lengthOfLongestSubstring(s)); - } -} From 0fe8a753ab038b65fbba524497e62f78fd5aefcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Thu, 21 May 2020 11:49:25 +0800 Subject: [PATCH 33/61] =?UTF-8?q?=E5=88=A0=E9=99=A4=E9=93=BE=E8=A1=A8?= =?UTF-8?q?=E7=9A=84=E5=80=92=E6=95=B0=E7=AC=AC=C2=A0n=C2=A0=E4=B8=AA?= =?UTF-8?q?=E8=8A=82=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../algorithm/study/demo/algorithm/leetcode/Solution7.java | 7 +++++++ .../algorithm/study/demo/algorithm/leetcode/Solution8.java | 1 + 2 files changed, 8 insertions(+) diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java index 6c8265c..691d9a1 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java @@ -30,6 +30,11 @@ public static class ListNode { /** * 快慢指针遍历连表。看是否相遇。如果相遇在判断是否是循环链表。 + * p1=x+y + * p2=x+y+z+y; + * 因为p2是p1的两倍 + * 2*(x+y)=x+y+z+y + * x=z * @param head * @return */ @@ -37,6 +42,7 @@ public static ListNode detectCycle(ListNode head) { if (null== head || head.next==null){ return null; } + //p1指针走一步、p2指针走两步。如果相等就表示是环形。 ListNode p1=head; ListNode p2=head; while(p2!=null && p2.next!=null){ @@ -50,6 +56,7 @@ public static ListNode detectCycle(ListNode head) { if (p1!=p2){ return null; } + //p1指向头结点。找到环形入口 p1=head; while(p1!=p2){ p1=p1.next; diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution8.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution8.java index e160ac7..f791dc5 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution8.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution8.java @@ -31,6 +31,7 @@ public static ListNode removeNthFromEnd(ListNode head, int n) { if (head.next==null){ return null; } + //增加一个头部节点,方便删除第一个节点。 ListNode temp=new ListNode(-1); temp.next=head; ListNode p1=temp; From 21dc9701cc426c5914ea48b8912ca3556288696a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Thu, 21 May 2020 12:01:27 +0800 Subject: [PATCH 34/61] =?UTF-8?q?=E9=93=BE=E8=A1=A8=E7=8E=AF=E5=BD=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution7.java | 20 ++++++++----------- 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java index 691d9a1..39e52f6 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution7.java @@ -49,20 +49,16 @@ public static ListNode detectCycle(ListNode head) { p1=p1.next; p2=p2.next.next; if(p1==p2){ - break; + //p1指向头结点。找到环形入口 + p1=head; + while(p1!=p2){ + p1=p1.next; + p2=p2.next; + } + return p1; } } - //如果快慢指针没有相遇代表是无环链表 - if (p1!=p2){ - return null; - } - //p1指向头结点。找到环形入口 - p1=head; - while(p1!=p2){ - p1=p1.next; - p2=p2.next; - } - return p1; + return null; } public static void main(String[] args) { ListNode a=new ListNode(5); From 7085a7187b8741762c998d687f0c9071d010961e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Thu, 21 May 2020 15:42:17 +0800 Subject: [PATCH 35/61] =?UTF-8?q?=E5=9B=9E=E6=96=87=E5=AD=90=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution10.java | 58 ++++++++++++++++++ .../demo/algorithm/leetcode/Solution9.java | 59 +++++++++++++++++++ 2 files changed, 117 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution10.java create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution9.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution10.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution10.java new file mode 100644 index 0000000..21e3809 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution10.java @@ -0,0 +1,58 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +import com.alibaba.fastjson.JSON; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author xun2.liu + * @title: Solution10 + * @projectName algorithm-study + * @description: 给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。 + * + * 具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。 + * + * 示例 1: + * + * 输入: "abc" + * 输出: 3 + * 解释: 三个回文子串: "a", "b", "c". + * 示例 2: + * + * 输入: "aaa" + * 输出: 6 + * 说明: 6个回文子串: "a", "a", "a", "aa", "aa", "aaa". + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/palindromic-substrings + * @date 2020/5/21 15:34 + */ +public class Solution10 { + //通过中心扩散法查找回文字符串 + public static void huiwen(String s,int l,int r,List filter){ + while(l>=0 && r filter=new ArrayList(); + for(int i=0;i=0 && r=p1.length()?res:p1; + res=res.length()>=p2.length()?res:p2; + } + return res; + } + public static void main(String[] args) { + System.out.println(longestPalindrome("abc")); + } +} From c899c154b925611486b27cefcdd3da753db23840 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Thu, 21 May 2020 16:55:26 +0800 Subject: [PATCH 36/61] =?UTF-8?q?=E6=95=B0=E7=BB=84-=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution11.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution11.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution11.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution11.java new file mode 100644 index 0000000..6407b06 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution11.java @@ -0,0 +1,51 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +import com.alibaba.fastjson.JSON; + +/** + * @author xun2.liu + * @title: Solution11 + * @projectName algorithm-study + * @description: 给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。 + * + * 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 + * + * 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素 + * + * https://leetcode-cn.com/problems/remove-element + * @date 2020/5/21 16:15 + */ +public class Solution11 { + public static int removeElement1(int[] nums, int val) { + //双指针 + int i=0; + int n=nums.length; + while(i Date: Sun, 24 May 2020 19:26:35 +0800 Subject: [PATCH 37/61] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=C2=A0strStr()=C2=A0?= =?UTF-8?q?=E5=87=BD=E6=95=B0=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution12.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution12.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution12.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution12.java new file mode 100644 index 0000000..2ce8e9b --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution12.java @@ -0,0 +1,37 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * 实现 strStr() 函数。 + * + * 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。 + * + * 示例 1: + * + * 输入: haystack = "hello", needle = "ll" + * 输出: 2 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/implement-strstr + */ +public class Solution12 { + public static int strStr(String haystack, String needle) { + int len=haystack.length(); + int n=needle.length(); + if (n>len){ + return -1; + } + if (len==n && haystack.equals(needle)){ + return 0; + } + for (int i=0;i Date: Sun, 24 May 2020 21:47:51 +0800 Subject: [PATCH 38/61] leetcode --- .../study/demo/algorithm/leetcode/Solution.java | 4 +++- .../study/demo/algorithm/leetcode/Solution11.java | 13 +------------ .../study/demo/algorithm/leetcode/Solution2.java | 2 +- .../study/demo/algorithm/leetcode/Solution3.java | 5 ++++- .../study/demo/algorithm/leetcode/Solution4.java | 4 +++- .../study/demo/algorithm/leetcode/Solution8.java | 2 +- .../study/demo/algorithm/leetcode/Solution9.java | 7 +++---- 7 files changed, 16 insertions(+), 21 deletions(-) diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution.java index 0c30ee1..97af0e9 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution.java @@ -67,8 +67,10 @@ public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { public static void main(String[] args) { ListNode a=new ListNode(5); ListNode b=new ListNode(5); + a.next=b; - ListNode result = addTwoNumbers(a, b); + + ListNode result = addTwoNumbers(a, a); for (ListNode node=result;node!=null;node=node.next){ System.out.println(node.val); } diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution11.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution11.java index 6407b06..9d3f841 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution11.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution11.java @@ -33,19 +33,8 @@ public static int removeElement1(int[] nums, int val) { } return i; } - public static int removeElement2(int[] nums, int val) { - //双指针-覆盖 - int n=0; - for (int i = 0; i < nums.length; i++) { - if (nums[n]!=val){ - nums[n]=nums[i]; - n++; - } - } - return n; - } public static void main(String[] args) { int[] nums=new int[]{3,2,2,1}; - System.out.println(removeElement2(nums,2)); + System.out.println(removeElement1(nums,3)); } } diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution2.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution2.java index 611281a..9ce2630 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution2.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution2.java @@ -41,7 +41,7 @@ public static int lengthOfLongestSubstring(String s) { for(int end=0;end> temp=new ArrayList<>(); @@ -23,6 +24,7 @@ public static String function(int a, int b){ remainder= a%b; for (int i=0;i integerIntegerMap = temp.get(i); + //如果相除得到的整数答案和余数在之前出现过,那么就会开始循环。也就是循环节点 if (integerIntegerMap.containsKey(value) && integerIntegerMap.containsValue(remainder)){ flag=true; break; @@ -45,7 +47,7 @@ public static String function(int a, int b){ } public static void main(String[] args) { - System.out.println(function(1,7)); + System.out.println(function(3,7)); } } diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution8.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution8.java index f791dc5..2a6a300 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution8.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution8.java @@ -31,7 +31,7 @@ public static ListNode removeNthFromEnd(ListNode head, int n) { if (head.next==null){ return null; } - //增加一个头部节点,方便删除第一个节点。 + //增加一个头部节点,方便删除倒数的节点刚好是第一个节点。 ListNode temp=new ListNode(-1); temp.next=head; ListNode p1=temp; diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution9.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution9.java index ad2166f..eb53604 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution9.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution9.java @@ -43,17 +43,16 @@ public static String longestPalindrome(String s) { } String res=""; for (int i=0;i=p1.length()?res:p1; res=res.length()>=p2.length()?res:p2; } return res; } public static void main(String[] args) { - System.out.println(longestPalindrome("abc")); + System.out.println(longestPalindrome("babad")); } } From d69f9188469c1c3635e4e86ae8a8eb2bcbc366b9 Mon Sep 17 00:00:00 2001 From: liuxun <553798608@qq.com> Date: Sun, 24 May 2020 23:41:13 +0800 Subject: [PATCH 39/61] =?UTF-8?q?=E7=88=AC=E6=A5=BC=E6=A2=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution13.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution13.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution13.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution13.java new file mode 100644 index 0000000..31f6945 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution13.java @@ -0,0 +1,59 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 + * + * 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? + * + * 注意:给定 n 是一个正整数。 + * + * 示例 1: + * + * 输入: 2 + * 输出: 2 + * 解释: 有两种方法可以爬到楼顶。 + * 1. 1 阶 + 1 阶 + * 2. 2 阶 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/climbing-stairs + */ +public class Solution13 { + /** + * 不难发现,这个问题可以被分解为一些包含最优子结构的子问题,即它的最优解可以从其子问题的最优解来有效地构建,我们可以使用动态规划来解决这一问题。 + * + * 第 i阶可以由以下两种方法得到: + * + * 在第 (i-1)阶后向上爬 1 阶。 + * + * 在第 (i-2)阶后向上爬 2 阶。 + * + * 所以到达第 i 阶的方法总数就是到第 (i-1)阶和第 (i-2)阶的方法数之和。 + * + * 令 dp[i] 表示能到达第 i 阶的方法总数: + * + * dp[i]=dp[i-1]+dp[i-2] + * + * @param n + * @return + */ + public static int climbStairs(int n) { + if (n<=0){ + return 0; + } + int[] dp=new int[n+1]; + dp[1]=1; + dp[2]=2; + if (n<=2){ + return dp[n]; + } + for (int i = 3; i <=n; i++) { + dp[i]=dp[i-1]+dp[i-2]; + } + return dp[n]; + } + + public static void main(String[] args) { + System.out.println(climbStairs(10)); + } +} From f94d10ff337faf9e4e021f2dee2bdbfe85142bf0 Mon Sep 17 00:00:00 2001 From: liuxun <553798608@qq.com> Date: Sun, 24 May 2020 23:45:27 +0800 Subject: [PATCH 40/61] =?UTF-8?q?=E7=88=AC=E6=A5=BC=E6=A2=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../study/demo/algorithm/leetcode/Solution13.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution13.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution13.java index 31f6945..4903320 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution13.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution13.java @@ -41,12 +41,15 @@ public static int climbStairs(int n) { if (n<=0){ return 0; } + if (n==1){ + return 1; + } + if (n==2){ + return 2; + } int[] dp=new int[n+1]; dp[1]=1; dp[2]=2; - if (n<=2){ - return dp[n]; - } for (int i = 3; i <=n; i++) { dp[i]=dp[i-1]+dp[i-2]; } @@ -54,6 +57,6 @@ public static int climbStairs(int n) { } public static void main(String[] args) { - System.out.println(climbStairs(10)); + System.out.println(climbStairs(1)); } } From 8d9757e15fe704ea3af9ce98fc31ac44d7ea0272 Mon Sep 17 00:00:00 2001 From: liuxun <553798608@qq.com> Date: Tue, 26 May 2020 23:34:08 +0800 Subject: [PATCH 41/61] =?UTF-8?q?=E4=B8=A4=E4=B8=AA=E5=8D=87=E5=BA=8F?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E5=90=88=E5=B9=B6=E4=B8=BA=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E6=96=B0=E7=9A=84=E5=8D=87=E5=BA=8F=E9=93=BE=E8=A1=A8=E5=B9=B6?= =?UTF-8?q?=E8=BF=94=E5=9B=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution14.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution14.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution14.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution14.java new file mode 100644 index 0000000..61d6cde --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution14.java @@ -0,0 +1,56 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * 将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。  + * + * 示例: + * + * 输入:1->2->4, 1->3->4 + * 输出:1->1->2->3->4->4 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/merge-two-sorted-lists + */ +public class Solution14 { + public static class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } + } + public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { + //需要返回排序好的节点 + ListNode result=new ListNode(-1); + //哨兵节点 + ListNode prev=result; + //首先遍历两个链表比较大小如果l1比l2小。l1往前走否则l2往前走。并且把值小的节点赋值给prev.next。 + while(l1!=null && l2!=null){ + if(l1.val Date: Wed, 27 May 2020 19:57:28 +0800 Subject: [PATCH 42/61] =?UTF-8?q?=E7=BB=99=E5=AE=9A=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=20s=20=E5=92=8C=20t=20=EF=BC=8C=E5=88=A4=E6=96=AD=20s?= =?UTF-8?q?=20=E6=98=AF=E5=90=A6=E4=B8=BA=20t=20=E7=9A=84=E5=AD=90?= =?UTF-8?q?=E5=BA=8F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution12.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution12.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution12.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution12.java new file mode 100644 index 0000000..ed48905 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution12.java @@ -0,0 +1,54 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * @author xun2.liu + * @title: Solution12 + * @projectName algorithm-study + * @description: 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 + * + * 你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。 + * + * 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。 + * + * 示例 1: + * s = "abc", t = "ahbgdc" + * + * 返回 true. + * + * 示例 2: + * s = "axc", t = "ahbgdc" + * + * 返回 false. + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/is-subsequence + * @date 2020/5/27 19:54 + */ +public class Solution12 { + /** + * 使用双指针i、n,如果s.charAt(i)等于t.charAt(n)的话,i、n指针都往前走。最后判断相等的次数是否等于s字符串的长度。 + * @param s + * @param t + * @return + */ + public static boolean isSubsequence(String s, String t) { + int i=0; + int n=0; + while(i Date: Wed, 27 May 2020 19:59:39 +0800 Subject: [PATCH 43/61] =?UTF-8?q?=E7=BB=99=E5=AE=9A=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=20s=20=E5=92=8C=20t=20=EF=BC=8C=E5=88=A4=E6=96=AD=20s?= =?UTF-8?q?=20=E6=98=AF=E5=90=A6=E4=B8=BA=20t=20=E7=9A=84=E5=AD=90?= =?UTF-8?q?=E5=BA=8F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution15.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution15.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution15.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution15.java new file mode 100644 index 0000000..d684b12 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution15.java @@ -0,0 +1,54 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * @author xun2.liu + * @title: Solution15 + * @projectName algorithm-study + * @description: 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 + * 你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。 + * * + * * 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。 + * * + * * 示例 1: + * * s = "abc", t = "ahbgdc" + * * + * * 返回 true. + * * + * * 示例 2: + * * s = "axc", t = "ahbgdc" + * * + * * 返回 false. + * * + * * 来源:力扣(LeetCode) + * * 链接:https://leetcode-cn.com/problems/is-subsequence + * @date 2020/5/27 19:58 + */ +public class Solution15 { + /** + * 使用双指针i、n,如果s.charAt(i)等于t.charAt(n)的话,i、n指针都往前走。最后判断相等的次数是否等于s字符串的长度。 + * @param s + * @param t + * @return + */ + public static boolean isSubsequence(String s, String t) { + int i=0; + int n=0; + while(i Date: Thu, 28 May 2020 01:22:05 +0800 Subject: [PATCH 44/61] =?UTF-8?q?=E7=BB=99=E5=AE=9A=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=EF=BC=8C=E9=AA=8C=E8=AF=81=E5=AE=83?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E6=98=AF=E5=9B=9E=E6=96=87=E4=B8=B2=EF=BC=8C?= =?UTF-8?q?=E5=8F=AA=E8=80=83=E8=99=91=E5=AD=97=E6=AF=8D=E5=92=8C=E6=95=B0?= =?UTF-8?q?=E5=AD=97=E5=AD=97=E7=AC=A6=EF=BC=8C=E5=8F=AF=E4=BB=A5=E5=BF=BD?= =?UTF-8?q?=E7=95=A5=E5=AD=97=E6=AF=8D=E7=9A=84=E5=A4=A7=E5=B0=8F=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution16.java | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution16.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution16.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution16.java new file mode 100644 index 0000000..f125ae6 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution16.java @@ -0,0 +1,67 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 + * + * 说明:本题中,我们将空字符串定义为有效的回文串。 + * + * 示例 1: + * + * 输入: "A man, a plan, a canal: Panama" + * 输出: true + * 示例 2: + * + * 输入: "race a car" + * 输出: false + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/valid-palindrome + */ +public class Solution16 { + /** + * 使用双指针对比字符相等 + * @param s + * @param l + * @param r + * @return + */ + public static boolean palindrome(String s,int l,int r){ + String news=s.toLowerCase(); + while(l Date: Thu, 28 May 2020 15:59:21 +0800 Subject: [PATCH 45/61] =?UTF-8?q?=E4=B8=A4=E6=95=B0=E4=B9=8B=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution17.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution17.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution17.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution17.java new file mode 100644 index 0000000..f28c940 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution17.java @@ -0,0 +1,45 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author xun2.liu + * @title: Solution17 + * @projectName algorithm-study + * @description: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 + * + * 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 + + * 示例: + * + * 给定 nums = [2, 7, 11, 15], target = 9 + * + * 因为 nums[0] + nums[1] = 2 + 7 = 9 + * 所以返回 [0, 1] + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/two-sum + * @date 2020/5/28 15:54 + */ +public class Solution17 { + public static int[] twoSum(int[] nums, int target) { + Map map= new HashMap<>(); + for(int i=0;i Date: Thu, 28 May 2020 22:50:08 +0800 Subject: [PATCH 46/61] =?UTF-8?q?=E7=BB=99=E5=AE=9A=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=EF=BC=8C=E6=89=BE=E5=87=BA=E5=85=B6?= =?UTF-8?q?=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution18.java | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution18.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution18.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution18.java new file mode 100644 index 0000000..7238868 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution18.java @@ -0,0 +1,81 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +import java.util.LinkedList; +import java.util.Queue; + +/** + 给定一个二叉树,找出其最大深度。 + * + 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 + * + 说明: 叶子节点是指没有子节点的节点。 + * + 示例: + 给定二叉树 [3,9,20,null,null,15,7], + * + 3 + / \ + 9 20 + / \ + 15 7 + 返回它的最大深度 3 。 + * + 来源:力扣(LeetCode) + 链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree + */ +public class Solution18 { + public static class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } + } + + /** + * 我们的想法是使用 DFS(深度优先搜索) 策略访问每个结点,同时在每次访问时更新最大深度。 + * 利用队列的方式访问树,每次遍历树的一层。深度就+1。 + * @param root + * @return + */ + public static int maxDepth(TreeNode root) { + if (null==root){ + return 0; + } + Queue queue=new LinkedList<>(); + //把当前的第一层添加至队列中 + queue.offer(root); + //默认深度为0 + int depth=0; + while (queue.size()>0){ + //获取当前层的节点数量 + int size = queue.size(); + //遍历当前层的节点 + for (int i = 0; i < size; i++) { + //弹出当前层的节点。获取节点下一层的节点 + TreeNode head = queue.poll(); + if (head.left!=null){ + queue.offer(head.left); + } + if (head.right!=null){ + queue.offer(head.right); + } + } + //当前层遍历结束后。树的深度+1 + depth++; + } + return depth; + + } + public static void main(String[] args) { + TreeNode a=new TreeNode(3); + TreeNode b=new TreeNode(9); + TreeNode c=new TreeNode(20); + TreeNode d=new TreeNode(15); + TreeNode r=new TreeNode(7); + a.left=b; + a.right=c; + c.left=d; + c.right=r; + System.out.println(maxDepth(a)); + } +} From 5d0d2b955f04f5b53eeb4989d90700b30e4f9ab3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Fri, 29 May 2020 18:39:56 +0800 Subject: [PATCH 47/61] =?UTF-8?q?=20=E7=BB=99=E5=AE=9A=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=EF=BC=8C=E8=BF=94=E5=9B=9E=E5=AE=83?= =?UTF-8?q?=E7=9A=84=E4=B8=AD=E5=BA=8F=C2=A0=E9=81=8D=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution19.java | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java new file mode 100644 index 0000000..cd9f1e9 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java @@ -0,0 +1,68 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +/** + * @author xun2.liu + * @title: Solution19 + * @projectName algorithm-study + * @description: 给定一个二叉树,返回它的中序 遍历。 + * + * 示例: + * + * 输入: [1,null,2,3] + * 1 + * \ + * 2 + * / + * 3 + * + * 输出: [1,3,2] + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal + * @date 2020/5/29 18:31 + */ +public class Solution19 { + public static class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } + } + public static List inorderTraversal(TreeNode root) { + List result=new ArrayList(); + Stack stack=new Stack(); + TreeNode curr=root; + while(curr!=null || !stack.isEmpty()){ + //先遍历左子树 + while(curr!=null){ + stack.push(curr); + curr=curr.left; + } + //取出栈顶的节点并且赋给指针 + curr=stack.pop(); + result.add(curr.val); + //然后取出右子树节点 + curr=curr.right; + } + return result; + } + public static void main(String[] args) { + TreeNode a=new TreeNode(3); + TreeNode b=new TreeNode(9); + TreeNode c=new TreeNode(20); + TreeNode d=new TreeNode(15); + TreeNode r=new TreeNode(2); + a.left=b; + a.right=c; + c.left=d; + c.right=r; + List integers = inorderTraversal(a); + for (Integer integer : integers) { + System.out.println(integer); + } + } +} From 89e8b928eff8a8c64c52f506f359ae8e056a2dff Mon Sep 17 00:00:00 2001 From: liuxun <553798608@qq.com> Date: Sun, 31 May 2020 00:35:43 +0800 Subject: [PATCH 48/61] =?UTF-8?q?=E5=8F=AA=E5=87=BA=E7=8E=B0=E4=B8=80?= =?UTF-8?q?=E6=AC=A1=E7=9A=84=E6=95=B0=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution20.java | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution20.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution20.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution20.java new file mode 100644 index 0000000..145c614 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution20.java @@ -0,0 +1,48 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。 + * + * 说明: + * + * 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? + * + * 示例 1: + * + * 输入: [2,2,1] + * 输出: 1 + * 示例 2: + * + * 输入: [4,1,2,1,2] + * 输出: 4 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/single-number + */ +public class Solution20 { + + /** + * 任何数字跟自己进行异或都等于0,0跟任何数字异或都等于该数字本身。 + * 所以把数组中的数字进行异或最后得到的肯定是一个不重复的数字,因为重复的数字都是两两出现。 + * 公式:a^b^a=b + * @param nums + * @return + */ + public static int singleNumber(int[] nums) { + if(nums.length==0){ + return -1; + } + if(nums.length==1){ + return nums[0]; + } + int result=0; + for(int num:nums){ + result ^= num; + } + return result; + } + + public static void main(String[] args) { + System.out.println(singleNumber(new int[]{2, 2, 1})); + } +} From 0c4e10890e764f4bc2fbb599288d8119e1fa2a46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Mon, 1 Jun 2020 14:09:02 +0800 Subject: [PATCH 49/61] solution --- .../study/demo/algorithm/leetcode/Solution13.java | 7 ------- .../study/demo/algorithm/leetcode/Solution19.java | 8 ++++++++ .../study/demo/algorithm/leetcode/Solution2.java | 4 ++-- .../study/demo/algorithm/leetcode/Solution20.java | 2 -- .../study/demo/algorithm/leetcode/Solution7.java | 3 ++- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution13.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution13.java index 4903320..0e7c65d 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution13.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution13.java @@ -21,19 +21,12 @@ public class Solution13 { /** * 不难发现,这个问题可以被分解为一些包含最优子结构的子问题,即它的最优解可以从其子问题的最优解来有效地构建,我们可以使用动态规划来解决这一问题。 - * * 第 i阶可以由以下两种方法得到: - * * 在第 (i-1)阶后向上爬 1 阶。 - * * 在第 (i-2)阶后向上爬 2 阶。 - * * 所以到达第 i 阶的方法总数就是到第 (i-1)阶和第 (i-2)阶的方法数之和。 - * * 令 dp[i] 表示能到达第 i 阶的方法总数: - * * dp[i]=dp[i-1]+dp[i-2] - * * @param n * @return */ diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java index cd9f1e9..62db890 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java @@ -32,6 +32,14 @@ public static class TreeNode { TreeNode right; TreeNode(int x) { val = x; } } + + /** + * 前序遍历:打印-左-右 + * 中序遍历:左-打印-右 + * 后序遍历:左-右-打印 + * @param root + * @return + */ public static List inorderTraversal(TreeNode root) { List result=new ArrayList(); Stack stack=new Stack(); diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution2.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution2.java index 9ce2630..5eae01b 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution2.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution2.java @@ -41,7 +41,7 @@ public static int lengthOfLongestSubstring(String s) { for(int end=0;end Date: Mon, 1 Jun 2020 14:31:57 +0800 Subject: [PATCH 50/61] =?UTF-8?q?=E7=BB=99=E5=AE=9A=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=EF=BC=8C=E8=BF=94=E5=9B=9E=E5=AE=83?= =?UTF-8?q?=E7=9A=84=E4=B8=AD=E5=BA=8F=C2=A0=E9=81=8D=E5=8E=86=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution19.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java index 62db890..16cf879 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java @@ -45,16 +45,19 @@ public static List inorderTraversal(TreeNode root) { Stack stack=new Stack(); TreeNode curr=root; while(curr!=null || !stack.isEmpty()){ - //先遍历左子树 - while(curr!=null){ + //首先遍历左子节点 + if (curr!=null){ + //不断往左子树方向走,每走一次就将当前节点保存到栈中 + //这是模拟递归的调用 stack.push(curr); curr=curr.left; + }else{ + //当前节点为空,说明左边走到头了,从栈中弹出节点并保存 + //然后转向右边节点,继续上面整个过程 + TreeNode popNode = stack.pop(); + result.add(popNode.val); + curr=curr.right; } - //取出栈顶的节点并且赋给指针 - curr=stack.pop(); - result.add(curr.val); - //然后取出右子树节点 - curr=curr.right; } return result; } From 83fcdb9baca8c509cd3478d018b83e0d4efc2fa9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Mon, 1 Jun 2020 14:50:58 +0800 Subject: [PATCH 51/61] =?UTF-8?q?=E7=BB=99=E5=AE=9A=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=EF=BC=8C=E8=BF=94=E5=9B=9E=E5=AE=83?= =?UTF-8?q?=E7=9A=84=E4=B8=AD=E5=BA=8F=C2=A0=E9=81=8D=E5=8E=86=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../algorithm/study/demo/algorithm/leetcode/Solution19.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java index 16cf879..df36d40 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution19.java @@ -54,8 +54,8 @@ public static List inorderTraversal(TreeNode root) { }else{ //当前节点为空,说明左边走到头了,从栈中弹出节点并保存 //然后转向右边节点,继续上面整个过程 - TreeNode popNode = stack.pop(); - result.add(popNode.val); + curr= stack.pop(); + result.add(curr.val); curr=curr.right; } } From 84c7bebd7e8a31e4dd80774fade508bd467bec8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Tue, 2 Jun 2020 15:00:22 +0800 Subject: [PATCH 52/61] =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E8=BD=AC?= =?UTF-8?q?=E6=8D=A2=E6=95=B4=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution21.java | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution21.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution21.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution21.java new file mode 100644 index 0000000..58e4050 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution21.java @@ -0,0 +1,83 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * @author xun2.liu + * @title: Solution21 + * @projectName algorithm-study + * @description: 字符串转换整数 (atoi) + * 请你来实现一个 atoi 函数,使其能将字符串转换成整数。 + * + * 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。接下来的转化规则如下: + * + * 如果第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字字符组合起来,形成一个有符号整数。 + * 假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成一个整数。 + * 该字符串在有效的整数部分之后也可能会存在多余的字符,那么这些字符可以被忽略,它们对函数不应该造成影响。 + * 注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换,即无法进行有效转换。 + * + * 在任何情况下,若函数不能进行有效的转换时,请返回 0 。 + * + * 提示: + * + * 本题中的空白字符只包括空格字符 ' ' 。 + * 假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 [−231,  231 − 1]。如果数值超过这个范围,请返回  INT_MAX (231 − 1) 或 INT_MIN (−231) 。 + *   + * 示例 1: + * + * 输入: "42" + * 输出: 42 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/string-to-integer-atoi + * @date 2020/6/2 11:49 + */ +public class Solution21 { + public static int myAtoi(String str) { + if(str==null) { + return 0; + } + int n = str.length(); + int i = 0; + int res = 0; + boolean is_negative = false; + //第一步,跳过前面若干个空格 + while(i='0' && str.charAt(i)<='9') { + //'0'的ASCII码是48,'1'的是49,这么一减就从就可以得到真正的整数值 + int tmp = str.charAt(i)-48; + //判断是否大于 最大32位整数 + if(!is_negative &&(res>Integer.MAX_VALUE ||(res==Integer.MAX_VALUE && tmp>=7))) { + return Integer.MAX_VALUE; + } + //判断是否小于 最小32位整数 + if(is_negative &&(-res<-Integer.MAX_VALUE || (-res==-Integer.MAX_VALUE && tmp>=8))) { + return -Integer.MAX_VALUE; + } + res = res*10 + tmp; + ++i; + } + //如果有负号标记则返回负数 + if(is_negative) { + return -res; + } + return res; + } + + public static void main(String[] args) { + System.out.println(myAtoi("-42")); + } +} From a18b2e57e2991f398b21aa6b636797462771401b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Wed, 3 Jun 2020 20:11:50 +0800 Subject: [PATCH 53/61] =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E5=8E=8B?= =?UTF-8?q?=E7=BC=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution22.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution22.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution22.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution22.java new file mode 100644 index 0000000..836babf --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution22.java @@ -0,0 +1,46 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * @author xun2.liu + * @title: Solution22 + * @projectName algorithm-study + * @description: 字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。 + * 比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。 + * 你可以假设字符串中只包含大小写英文字母(a至z)。 + * 示例1: + * + * 输入:"aabcccccaaa" + * 输出:"a2b1c5a3" + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/compress-string-lcci + * @date 2020/6/3 20:07 + */ +public class Solution22 { + public static String compressString(String S) { + //慢指针 + int i=0; + int len=S.length(); + //压缩后的字符串 + StringBuilder sb=new StringBuilder(); + while(i Date: Fri, 5 Jun 2020 14:08:22 +0800 Subject: [PATCH 54/61] =?UTF-8?q?=E6=95=B0=E7=BB=84=E5=8D=87=E5=BA=8F?= =?UTF-8?q?=E6=8E=92=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/algorithm/study/demo/Demo1.java | 14 +--- .../study/demo/algorithm/SortProject.java | 22 +++--- .../demo/algorithm/leetcode/Solution23.java | 79 +++++++++++++++++++ 3 files changed, 93 insertions(+), 22 deletions(-) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution23.java diff --git a/src/main/java/com/algorithm/study/demo/Demo1.java b/src/main/java/com/algorithm/study/demo/Demo1.java index dcbb121..089d5e4 100644 --- a/src/main/java/com/algorithm/study/demo/Demo1.java +++ b/src/main/java/com/algorithm/study/demo/Demo1.java @@ -12,16 +12,8 @@ */ public class Demo1 { public static void main(String[] args) throws Exception { -// String str="2020-01-07 19:42:06.386 INFO [BUS_VCC_ORDER_DETAIL][common][][BJ2001071650476613943652869165056][VCC20200107173708DDPSYV]PsiDAOProxy 类 listBySerialNo 方法入参:BJ2001071650476613943652869165056"; -// String traceId="VCC20200107173708DDPSYV"; -// String p="["+traceId+"]"; -// if (str.indexOf(p)>0){ -// str=StringUtils.substring(str,str.indexOf("["+traceId+"]")+p.length()); -// } -// System.out.println(str); - String msg="asdfasdf"; - String throwable="asdfasdfasdfadaskdjfaskdjf"; - msg+=throwable; - System.out.println(msg); + int i=0; +// System.out.println(i++); + System.out.println(++i); } } diff --git a/src/main/java/com/algorithm/study/demo/algorithm/SortProject.java b/src/main/java/com/algorithm/study/demo/algorithm/SortProject.java index 15348d9..ec90f5d 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/SortProject.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/SortProject.java @@ -61,17 +61,17 @@ public static void performanceTest(int len) throws Exception{ * 时间复杂度为O(n²) * 空间复杂度为O(1) */ - private static void maopaoSort(int score[]){ - System.out.println("排序前:"+ JSON.toJSONString(score)); - boolean flag=true;//数据发生了交换才继续冒泡 - for (int i = 1; i < score.length && flag; i++){ //最多做n-1趟排序 - flag=false; - for(int j = 0 ;j < score.length - i; j++){ //对当前无序区间score[0......length-i-1]进行排序(j的范围很关键,这个范围是在逐步缩小的) - if(score[j] > score[j + 1]){ //把大或者小的值交换到后面 - int temp = score[j]; - score[j] = score[j + 1]; - score[j + 1] = temp; - flag=true;//发生了数据交换 + private static void maopaoSort(int score[]){ + System.out.println("排序前:"+ JSON.toJSONString(score)); + boolean flag=true;//数据发生了交换才继续冒泡 + for (int i = 1; i < score.length && flag; i++){ //最多做n-1趟排序 + flag=false; + for(int j = 0 ;j < score.length - i; j++){ //对当前无序区间score[0......length-i-1]进行排序(j的范围很关键,这个范围是在逐步缩小的) + if(score[j] > score[j + 1]){ //把大或者小的值交换到后面 + int temp = score[j]; + score[j] = score[j + 1]; + score[j + 1] = temp; + flag=true;//发生了数据交换 } } } diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution23.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution23.java new file mode 100644 index 0000000..b770a6a --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution23.java @@ -0,0 +1,79 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +import java.util.Arrays; + +/** + * @author xun2.liu + * @title: Solution23 + * @projectName algorithm-study + * @description: 给你一个整数数组 nums,请你将该数组升序排列。 + * + * 示例 1: + * + * 输入:nums = [5,2,3,1] + * 输出:[1,2,3,5] + * @date 2020/6/5 13:50 + */ +public class Solution23 { + /** + * 归并排序 + * https://www.cnblogs.com/chengxiao/p/6194356.html + * @param nums + * @return + */ + public static int[] sortArray(int[] nums) { + //在排序前,先建好一个长度等于原数组长度的临时数组,避免递归中频繁开辟空间 + int[] temp=new int[nums.length]; + mSort(nums,0,nums.length-1,temp); + return nums; + } + + public static void mSort(int[] nums,int left,int right,int[] temp){ + if (left Date: Wed, 10 Jun 2020 11:49:01 +0800 Subject: [PATCH 55/61] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=8E=92=E5=BA=8F?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E4=B8=AD=E7=9A=84=E9=87=8D=E5=A4=8D=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/algorithm/study/demo/Demo1.java | 19 ------- .../demo/algorithm/leetcode/Solution11.java | 2 - .../demo/algorithm/leetcode/Solution24.java | 53 +++++++++++++++++++ .../demo/algorithm/leetcode/Solution3.java | 1 - 4 files changed, 53 insertions(+), 22 deletions(-) delete mode 100644 src/main/java/com/algorithm/study/demo/Demo1.java create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution24.java diff --git a/src/main/java/com/algorithm/study/demo/Demo1.java b/src/main/java/com/algorithm/study/demo/Demo1.java deleted file mode 100644 index 089d5e4..0000000 --- a/src/main/java/com/algorithm/study/demo/Demo1.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.algorithm.study.demo; - -import org.apache.commons.lang3.StringUtils; - -import java.math.BigDecimal; - -/** - * @title: Demo1 - * @projectName algorithm-study - * @description: TODO - * @date 2019/9/24 15:59 - */ -public class Demo1 { - public static void main(String[] args) throws Exception { - int i=0; -// System.out.println(i++); - System.out.println(++i); - } -} diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution11.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution11.java index 9d3f841..f8d13a3 100644 --- a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution11.java +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution11.java @@ -1,7 +1,5 @@ package com.algorithm.study.demo.algorithm.leetcode; -import com.alibaba.fastjson.JSON; - /** * @author xun2.liu * @title: Solution11 diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution24.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution24.java new file mode 100644 index 0000000..9208a62 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution24.java @@ -0,0 +1,53 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * @author xun2.liu + * @title: Solution24 + * @projectName algorithm-study + * @description: 给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 + * + * 不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。 + + * 示例 1: + * + * 给定数组 nums = [1,1,2], + * + * 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 + * + * 你不需要考虑数组中超出新长度后面的元素。 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array + * @date 2020/6/10 11:33 + */ +public class Solution24 { + /** + * 解法: 双指针 + * 首先注意数组是有序的,那么重复的元素一定会相邻。 + * 要求删除重复元素,实际上就是将不重复的元素移到数组的左侧。 + * 考虑用 2 个指针,一个在前记作 p1,一个在后记作 p2,算法流程如下: + * 比较 p1 和 p2 位置的元素是否相等。 + * 如果相等,p2 后移 1 位 + * 如果不相等,将 p2 位置的元素复制到 p1+1 位置上,p1 后移一位,p2 后移 1 位 + * 重复上述过程,直到 p2 等于数组长度。 + * 返回 p1 + 1,即为新数组长度。 + * @param nums + * @return + */ + public static int removeDuplicates(int[] nums) { + int p1=0; + int p2=0; + while(p2 Date: Mon, 15 Jun 2020 17:21:02 +0800 Subject: [PATCH 56/61] =?UTF-8?q?=E6=9C=80=E9=95=BF=E5=85=AC=E5=85=B1?= =?UTF-8?q?=E5=89=8D=E7=BC=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution25.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution25.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution25.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution25.java new file mode 100644 index 0000000..ec6f948 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution25.java @@ -0,0 +1,59 @@ +package com.algorithm.study.demo.algorithm.leetcode; +//编写一个函数来查找字符串数组中的最长公共前缀。 +// +// 如果不存在公共前缀,返回空字符串 ""。 +// +// 示例 1: +// +// 输入: ["flower","flow","flight"] +//输出: "fl" +// +// +// 示例 2: +// +// 输入: ["dog","racecar","car"] +//输出: "" +//解释: 输入不存在公共前缀。 +// +// +// 说明: +// +// 所有输入只包含小写字母 a-z 。 +// Related Topics 字符串 + + +//leetcode submit region begin(Prohibit modification and deletion) +public class Solution25 { + public String longestCommonPrefix(String[] strs) { + if (strs.length==0){ + return ""; + } + //令最长公共前缀 ans 的值为第一个字符串,进行初始化 + String commonStr=strs[0]; + for (int i = 1; i < strs.length; i++) { + //进行匹配的字符串 + String str = strs[i]; + //公共前缀的下标 + int j=0; + for (;j Date: Thu, 18 Jun 2020 11:26:26 +0800 Subject: [PATCH 57/61] =?UTF-8?q?=E5=88=A0=E9=99=A4=E9=93=BE=E8=A1=A8?= =?UTF-8?q?=E4=B8=AD=E7=9A=84=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution26.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution26.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution26.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution26.java new file mode 100644 index 0000000..5b73e03 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution26.java @@ -0,0 +1,50 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +import com.alibaba.fastjson.JSON; + +/** + * @author xun2.liu + * @title: Solution26 + * @projectName algorithm-study + * @description: 删除链表中的元素 + * @date 2020/6/17 13:40 + */ +public class Solution26 { + public static class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } + } + public static ListNode delNode(ListNode head,int val){ + //首先删除头结点等于val的节点 + while (head!=null && head.val==val){ + head=head.next; + } + if (head==null){ + return head; + } + //删除头结点后边等于val的节点 + ListNode temp=head; + while (temp.next!=null){ + if (temp.next.val==val){ + temp.next=temp.next.next; + }else{ + temp=temp.next; + } + } + return temp; + } + public static void main(String[] args) { + ListNode a=new ListNode(0); + ListNode b=new ListNode(1); + ListNode c=new ListNode(2); + a.next=b;b.next=c; + ListNode temp=a; + while (temp!=null){ + delNode(temp, 2); + temp=temp.next; + } + System.out.println(JSON.toJSONString(a)); + + } +} From b00b0ac7a3bba5befbc1e147478dbdcf0757b982 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Sun, 28 Jun 2020 12:05:40 +0800 Subject: [PATCH 58/61] =?UTF-8?q?=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/algorithm/study/demo/MainTest1.java | 36 ++++ .../demo/datastructure/linear/MLinkList.java | 184 ++++++++++-------- .../demo/datastructure/tree/LinkBinTree.java | 48 ++++- 3 files changed, 179 insertions(+), 89 deletions(-) create mode 100644 src/main/java/com/algorithm/study/demo/MainTest1.java diff --git a/src/main/java/com/algorithm/study/demo/MainTest1.java b/src/main/java/com/algorithm/study/demo/MainTest1.java new file mode 100644 index 0000000..0c3d776 --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/MainTest1.java @@ -0,0 +1,36 @@ +package com.algorithm.study.demo; + +import com.alibaba.fastjson.JSON; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +/** + * @author xun2.liu + * @title: MainTest1 + * @projectName algorithm-study + * @description: TODO + * @date 2020/6/24 17:30 + */ +public class MainTest1 { + public static void main(String[] args) { + List> lists=new ArrayList<>(); + if((lists.size() & 1)==1){ + LinkedList ls=new LinkedList<>(); + //奇数层放到队列尾部 + ls.addLast(3); + lists.add(ls); + }else{ + LinkedList ls=new LinkedList<>(); + //偶数层放到队列头部 + ls.addFirst(9); + ls.addFirst(2); + lists.add(ls); + } + + System.out.println(JSON.toJSONString(lists)); + System.out.println((2 & 1)); + + } +} diff --git a/src/main/java/com/algorithm/study/demo/datastructure/linear/MLinkList.java b/src/main/java/com/algorithm/study/demo/datastructure/linear/MLinkList.java index 24e70ba..94e67ab 100644 --- a/src/main/java/com/algorithm/study/demo/datastructure/linear/MLinkList.java +++ b/src/main/java/com/algorithm/study/demo/datastructure/linear/MLinkList.java @@ -19,113 +19,124 @@ public class Node { // 无参构造器 public Node() { } + // 初始化全部属性的构造器 public Node(E data, Node next) { this.value = data; this.next = next; } } + private Node data;// 保存头结点 - private int size=0;// 保存已含有的节点数 + private int size = 0;// 保存已含有的节点数 - public MLinkList(){ - this.data=null;//初始化一个空的头结点 + public MLinkList() { + this.data = null;//初始化一个空的头结点 } /** * 添加一个头结点 + * * @param element */ - public void addFirst(E element){ - if (data==null){ - data=new Node(element,null); - }else{ - Node temp=new Node(element,null); - temp.next=data; - data=temp; + public void addFirst(E element) { + if (data == null) { + data = new Node(element, null); + } else { + Node temp = new Node(element, null); + temp.next = data; + data = temp; } size++; } + /** * 删除一个头结点 + * * @return */ - public E deleteFirst(){ - Node current=data; - E val=current.value; - current.value=current.next.value; - current.next=current.next.next; + public E deleteFirst() { + Node current = data; + E val = current.value; + current.value = current.next.value; + current.next = current.next.next; return val; } /** * 在index插入节点 + * * @param index * @param element */ - public void add(int index,E element){ + public void add(int index, E element) { checkPositionIndex(index); - if (index==0){ + if (index == 0) { addFirst(element); return; } - Node newNode=new Node(element,null);//新的结点 - Node current=data;//保存index当前的结点 - int i=1;//默认是第i个结点 - while (isize-1){ - throw new IndexOutOfBoundsException("数组越界Index: "+index+", Size: "+size); + if (index < 0 || index > size - 1) { + throw new IndexOutOfBoundsException("数组越界Index: " + index + ", Size: " + size); } } - public int size(){ + + public int size() { return size; } @Override - public String toString(){ - StringBuilder sb=new StringBuilder(); - Node temp=data; - while (temp!=null){ + public String toString() { + StringBuilder sb = new StringBuilder(); + Node temp = data; + while (temp != null) { sb.append(temp.value); - temp= temp.next;//找到最后一个结点 + temp = temp.next;//找到最后一个结点 } return sb.toString(); } @@ -196,26 +212,26 @@ public String toString(){ /** * 反转链表O(n)复杂度实现 */ - public void reverseLinkedList(){ - if (data==null || data.next==null){ + public void reverseLinkedList() { + if (data == null || data.next == null) { return; } - Node p1=data; - Node p2=data.next; - Node p3=null; - while (p2!=null){ - p3=p2.next; - p2.next=p1; - p1=p2; - p2=p3; + Node p1 = data; + Node p2 = data.next; + Node p3 = null; + while (p2 != null) { + p3 = p2.next; + p2.next = p1; + p1 = p2; + p2 = p3; } - data.next=null; - data=p1; + data.next = null; + data = p1; System.out.println("反转完毕"); } public static void main(String[] args) { - MLinkList mLinkList=new MLinkList(); + MLinkList mLinkList = new MLinkList(); mLinkList.add(4); mLinkList.add(1); mLinkList.add(8); diff --git a/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java b/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java index 35e2c95..8bad3cb 100644 --- a/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java +++ b/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java @@ -318,11 +318,47 @@ public List> divOrderTraverse(TreeNode t){ } return levels; } + + public List> levelOrder(TreeNode root) { + if(root==null){ + return new ArrayList>(); + } + List> lists=new ArrayList<>(); + Queue queue=new LinkedList(); + queue.offer(root); + while(queue.size()>0){ + LinkedList levelList=new LinkedList<>(); + for(int i=queue.size();i>0;i--){ + TreeNode node=queue.poll(); + if((lists.size() & 1)==1){ + //奇数层放到队列尾部 + levelList.addLast(node.data); + }else{ + //偶数层放到队列头部 + levelList.addFirst(node.data); + } + if(node.right!=null){ + queue.offer(node.right); + } + if(node.left!=null){ + queue.offer(node.left); + } + } + lists.add(levelList); + } + return lists; + } + public void divOrderTraverse(){ List> lists = divOrderTraverse(root); System.out.println(JSON.toJSONString(lists)); } - /**区间搜索**/ + public void levelOrder() { + List> lists = levelOrder(root); + System.out.println(JSON.toJSONString(lists)); + } + + /**区间搜索**/ private void searchSection(TreeNode t,int k1,int k2,ArrayList result){ if (t==null){ return; @@ -403,13 +439,14 @@ public static void main(String[] args) { // linkBinTree.searchSection(linkBinTree.getRoot(),10,20,list); // System.out.println("区间查询"+list.toString()); System.out.println("-------------递归遍历----------------"); - linkBinTree.preOrderTraverse();//前序遍历 从根节点开始遍历 +// linkBinTree.preOrderTraverse();//前序遍历 从根节点开始遍历 System.out.println("-----------------------------"); - linkBinTree.inOrderTraverse();//中序遍历 从根节点开始 +// linkBinTree.inOrderTraverse();//中序遍历 从根节点开始 System.out.println("-----------------------------"); - linkBinTree.postOrderTraverse();//后序遍历 +// linkBinTree.postOrderTraverse();//后序遍历 System.out.println("-----------------------------"); - linkBinTree.divOrderTraverse();//层次遍历 +// linkBinTree.divOrderTraverse();//层次遍历 + linkBinTree.levelOrder(); // //前序遍历:根节点->左子树->右子树 // //中序遍历:左子树->根节点->右子树 @@ -425,6 +462,7 @@ public static void main(String[] args) { // TreeNode node = linkBinTree.find(9); // System.out.println(node.data); // System.out.println("最小值为:"+linkBinTree.findMin().data); + } } From b4ff0ffb53bb188c784637fa5782ac752358deee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Mon, 29 Jun 2020 20:41:29 +0800 Subject: [PATCH 59/61] =?UTF-8?q?=E5=BA=8F=E5=88=97=E5=8C=96=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/datastructure/tree/LinkBinTree.java | 451 +++++++++++------- 1 file changed, 291 insertions(+), 160 deletions(-) diff --git a/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java b/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java index 8bad3cb..a115304 100644 --- a/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java +++ b/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java @@ -6,24 +6,27 @@ import java.util.*; /** - * * 二叉搜索树链表存储 - 前序遍历:根节点->左子树->右子树 - 中序遍历:左子树->根节点->右子树 - 后序遍历:左子树->右子树->根节点 + * 前序遍历:根节点->左子树->右子树 + * 中序遍历:左子树->根节点->右子树 + * 后序遍历:左子树->右子树->根节点 * Created by liuxun on 2017/6/29. */ public class LinkBinTree { - public static class TreeNode{ + public static class TreeNode { Integer data;//节点数据 TreeNode left;//左子节点数据 TreeNode right;//右子节点数据 - TreeNode(){} - TreeNode(Integer data){ + + TreeNode() { + } + + TreeNode(Integer data) { this.data = data; this.left = null; this.right = null; } + public TreeNode(Integer data, TreeNode left, TreeNode right) { this.data = data; this.left = left; @@ -32,164 +35,194 @@ public TreeNode(Integer data, TreeNode left, TreeNode right) { } private TreeNode root; - /**初始化空的二叉树**/ - public LinkBinTree(){ - root=new TreeNode(); + + /** + * 初始化空的二叉树 + **/ + public LinkBinTree() { + root = new TreeNode(); } - /**指定一个默认的根二叉树**/ - public LinkBinTree(Integer d){ - root=new TreeNode(d); + + /** + * 指定一个默认的根二叉树 + **/ + public LinkBinTree(Integer d) { + root = new TreeNode(d); } - /**判断二叉树是否为空**/ - public boolean isEmpty(){ - return root.data==null; + + /** + * 判断二叉树是否为空 + **/ + public boolean isEmpty() { + return root.data == null; } - /**获取根节点**/ - public TreeNode getRoot(){ - if (isEmpty()){ + + /** + * 获取根节点 + **/ + public TreeNode getRoot() { + if (isEmpty()) { throw new RuntimeException("树为空,无法获取根节点"); } return root; } - /**获取树的深度**/ - public int getDeep(TreeNode t){ - if (t==null){ + /** + * 获取树的深度 + **/ + public int getDeep(TreeNode t) { + if (t == null) { return 0; } - int l=getDeep(t.left); - int r=getDeep(t.right); - return l>r?(l+1):(r+1); + int l = getDeep(t.left); + int r = getDeep(t.right); + return l > r ? (l + 1) : (r + 1); } - /**获取树的最小深度**/ - public int getMinDeep(TreeNode t){ - if (t==null){ + + /** + * 获取树的最小深度 + **/ + public int getMinDeep(TreeNode t) { + if (t == null) { return 0; } - if (t.left==null && t.right==null){ + if (t.left == null && t.right == null) { return 1; } - int l=getMinDeep(t.left); - int r=getMinDeep(t.right); - return lt.data){ - if(t.right!=null){ - add(t.right,value); - } - else{ + + private void add(TreeNode t, int value) { + if (value > t.data) { + if (t.right != null) { + add(t.right, value); + } else { t.right = new TreeNode(value); } - } - else{ - if(t.left!=null){ - add(t.left,value); - } - else{ + } else { + if (t.left != null) { + add(t.left, value); + } else { t.left = new TreeNode(value); } } } - private void add2(TreeNode t,int value){ - if(null==t.data){ - t.data=value; + + private void add2(TreeNode t, int value) { + if (null == t.data) { + t.data = value; return; } - TreeNode node=new TreeNode(value); - TreeNode current=t; - while(true){ - TreeNode parentNode=current; - if (current.data>value){ - current=current.left; - if (current==null){ - parentNode.left=node; + TreeNode node = new TreeNode(value); + TreeNode current = t; + while (true) { + TreeNode parentNode = current; + if (current.data > value) { + current = current.left; + if (current == null) { + parentNode.left = node; return; } - }else{ - current=current.right; - if (current==null){ - parentNode.right=node; + } else { + current = current.right; + if (current == null) { + parentNode.right = node; return; } } } } + /** * 递归从根节点开始插入数据,大于根节点放在右子树,小于根节点放在左子树 + * * @param value */ - public void add(int value){ - add(root,value); + public void add(int value) { + add(root, value); } + /** * 非递归模式插入数据 * 从根节点开始插入数据,大于根节点放在右子树,小于根节点放在左子树 + * * @param value */ - public void add2(int value){ - add2(root,value); + public void add2(int value) { + add2(root, value); } + /** * 前序遍历 * 如果树为空返回,如果不为空首先从根节点开始遍历,然后先前序遍历左子树,最后前序遍历右子树。 */ - public void preOrderTraverse(TreeNode t){ - if (t==null) { + public void preOrderTraverse(TreeNode t) { + if (t == null) { return; } System.out.println(t.data); preOrderTraverse(t.left); preOrderTraverse(t.right); } - public void preOrderTraverse(){ + + public void preOrderTraverse() { preOrderTraverse(root); } /** * 非递归前序遍历 + * * @param t */ public void preOrderTraverse2(TreeNode t) { - if (t==null) { + if (t == null) { return; } - Stack stack=new Stack<>(); - while(t!=null || !stack.isEmpty()){ - while (t!=null){ + Stack stack = new Stack<>(); + while (t != null || !stack.isEmpty()) { + while (t != null) { System.out.println(t.data); stack.push(t); - t=t.left; + t = t.left; } - if (!stack.isEmpty()){ - t=stack.pop(); - t=t.right; + if (!stack.isEmpty()) { + t = stack.pop(); + t = t.right; } } } - public void preOrderTraverse2(){ + + public void preOrderTraverse2() { preOrderTraverse2(root); } @@ -197,64 +230,71 @@ public void preOrderTraverse2(){ * 中序遍历 * 如果树为空返回,从根节点开始,中序遍历左子树,然后访问根节点,最后中序遍历右子树。 */ - public void inOrderTraverse(TreeNode t){ - if (t==null) { + public void inOrderTraverse(TreeNode t) { + if (t == null) { return; } inOrderTraverse(t.left); System.out.println(t.data); inOrderTraverse(t.right); } - public void inOrderTraverse(){ + + public void inOrderTraverse() { inOrderTraverse(root); } /** * 非递归中序遍历 + * * @param t */ - public void inOrderTraverse2(TreeNode t){ - if (t==null) { + public void inOrderTraverse2(TreeNode t) { + if (t == null) { return; } - Stack stack=new Stack<>(); - while (t!=null || !stack.isEmpty()){ - while (t!=null){ + Stack stack = new Stack<>(); + while (t != null || !stack.isEmpty()) { + while (t != null) { stack.push(t); - t=t.left; + t = t.left; } - if (!stack.isEmpty()){ - t=stack.pop(); + if (!stack.isEmpty()) { + t = stack.pop(); System.out.println(t.data); - t=t.right; + t = t.right; } } } - public void inOrderTraverse2(){ + + public void inOrderTraverse2() { inOrderTraverse2(root); } + /** * 后续遍历 + * * @param t */ - public void postOrderTraverse(TreeNode t){ - if (t==null) { + public void postOrderTraverse(TreeNode t) { + if (t == null) { return; } postOrderTraverse(t.left); postOrderTraverse(t.right); System.out.println(t.data); } - public void postOrderTraverse(){ + + public void postOrderTraverse() { postOrderTraverse(root); } /** * 非递归后续遍历 + * * @param root */ - public void postOrderTraverse2(TreeNode root){ + public void postOrderTraverse2(TreeNode root) { Stack s = new Stack(); Stack s2 = new Stack(); Integer i = new Integer(1); //0表示对应位置上的节点还没有遍历过右节点,1表示已经遍历过 @@ -277,39 +317,40 @@ public void postOrderTraverse2(TreeNode root){ } } } - public void postOrderTraverse2(){ + + public void postOrderTraverse2() { postOrderTraverse2(root); } + /** * 层级遍历 + * * @param t */ - public List> divOrderTraverse(TreeNode t){ - if (t==null) { + public List> divOrderTraverse(TreeNode t) { + if (t == null) { return new ArrayList>(); } //初始化队列只包含一个节点 root 和层次编号 0 : level = 0。 - List> levels= new ArrayList<>(); - Queue queue = new LinkedList() ; + List> levels = new ArrayList<>(); + Queue queue = new LinkedList(); queue.add(root); //树的层数 - int level=0; - while(queue.size() != 0) - { + int level = 0; + while (queue.size() != 0) { //插入一个空列表,开始当前层的算法。 levels.add(new ArrayList<>()); int len = queue.size(); //计算当前层有多少个元素:等于队列的长度。 - for(int i=0;i > divOrderTraverse(TreeNode t){ } public List> levelOrder(TreeNode root) { - if(root==null){ + if (root == null) { return new ArrayList>(); } - List> lists=new ArrayList<>(); - Queue queue=new LinkedList(); + List> lists = new ArrayList<>(); + Queue queue = new LinkedList(); queue.offer(root); - while(queue.size()>0){ - LinkedList levelList=new LinkedList<>(); - for(int i=queue.size();i>0;i--){ - TreeNode node=queue.poll(); - if((lists.size() & 1)==1){ + while (queue.size() > 0) { + LinkedList levelList = new LinkedList<>(); + for (int i = queue.size(); i > 0; i--) { + TreeNode node = queue.poll(); + if ((lists.size() & 1) == 1) { //奇数层放到队列尾部 levelList.addLast(node.data); - }else{ + } else { //偶数层放到队列头部 levelList.addFirst(node.data); } - if(node.right!=null){ + if (node.right != null) { queue.offer(node.right); } - if(node.left!=null){ + if (node.left != null) { queue.offer(node.left); } } @@ -349,44 +390,126 @@ public List> levelOrder(TreeNode root) { return lists; } - public void divOrderTraverse(){ + /** + * 层级遍历1 + */ + public void divOrderTraverse() { List> lists = divOrderTraverse(root); System.out.println(JSON.toJSONString(lists)); } + + /** + * 层级遍历2 + */ public void levelOrder() { List> lists = levelOrder(root); System.out.println(JSON.toJSONString(lists)); } - /**区间搜索**/ - private void searchSection(TreeNode t,int k1,int k2,ArrayList result){ - if (t==null){ + /** + * 序列化树 + * + * @param root + * @return + */ + public String serialize(TreeNode root) { + if (root == null) { + return null; + } + //使用层序遍历 + Queue que = new LinkedList(); + StringBuilder sb = new StringBuilder("["); + que.add(root); + while (que.size() > 0) { + int currSize = que.size(); + for (int i = 0; i < currSize; i++) { + TreeNode node = que.poll(); + if (node != null) { + sb.append(node.data).append(","); + que.add(node.left); + que.add(node.right); + } else { + sb.append("null,"); + } + } + } + return sb.deleteCharAt(sb.length() - 1).append("]").toString(); + } + + public String serialize() { + String serialize = serialize(root); + System.out.println(serialize); + return serialize; + } + + // Decodes your encoded data to tree. + public TreeNode deserialize(String data) { + if (data == null || data.length() == 0) { + return null; + } + data = data.substring(1, data.length() - 1); + String[] arrData = data.split(","); + //填充根节点 + TreeNode tree = new TreeNode(Integer.valueOf(arrData[0])); + Queue que = new LinkedList<>(); + que.add(tree); + int i = 1; + while (que.size() > 0 && i < arrData.length) { + TreeNode currNode = que.poll(); + + if (arrData[i].equals("null")) { + currNode.left = null; + } else { + TreeNode treeLeft = new TreeNode(Integer.valueOf(arrData[i])); + currNode.left = treeLeft; + que.add(treeLeft); + } + i++; + + if (arrData[i].equals("null")) { + currNode.right = null; + } else { + TreeNode treeRight = new TreeNode(Integer.valueOf(arrData[i])); + currNode.right = treeRight; + que.add(treeRight); + } + i++; + } + return tree; + } + + /** + * 区间搜索 + **/ + private void searchSection(TreeNode t, int k1, int k2, ArrayList result) { + if (t == null) { return; } - if(t.data>k1){ - searchSection(t.left,k1,k2,result); + if (t.data > k1) { + searchSection(t.left, k1, k2, result); } - if(t.data>=k1&&t.data<=k2){ + if (t.data >= k1 && t.data <= k2) { result.add(t.data); } - if(t.datakey){ - currnode=currnode.left; - }else if (currnode.data key) { + currnode = currnode.left; + } else if (currnode.data < key) { + currnode = currnode.right; + } else { return currnode; } } @@ -395,39 +518,42 @@ public TreeNode find(int key){ /** * 查找最小值 + * * @return */ - public TreeNode findMin(){ - TreeNode current=root; - TreeNode minNode=current; - while(current!=null){ - minNode=current; - current=current.left; + public TreeNode findMin() { + TreeNode current = root; + TreeNode minNode = current; + while (current != null) { + minNode = current; + current = current.left; } return minNode; } /** * 查找最大值 + * * @return */ - public TreeNode findMax(){ - TreeNode current=root; - TreeNode maxNode=current; - while(current!=null){ - maxNode=current; - current=current.right; + public TreeNode findMax() { + TreeNode current = root; + TreeNode maxNode = current; + while (current != null) { + maxNode = current; + current = current.right; } return maxNode; } + public static void main(String[] args) { - int[] ls=new int[]{30,9,8,33,45,11,55,66}; - LinkBinTree linkBinTree=new LinkBinTree(); - for (int i=0;i左子树->右子树 // //中序遍历:左子树->根节点->右子树 // //后序遍历:左子树->右子树->根节点 @@ -458,7 +589,7 @@ public static void main(String[] args) { // linkBinTree.inOrderTraverse2();//中序遍历 // System.out.println("-----------------------------"); // linkBinTree.postOrderTraverse2();//后序遍历 - //二叉查找树搜索 + //二叉查找树搜索 // TreeNode node = linkBinTree.find(9); // System.out.println(node.data); // System.out.println("最小值为:"+linkBinTree.findMin().data); From f30685f822132b4e3eb05e86addb1b51bd5305d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Mon, 29 Jun 2020 20:43:48 +0800 Subject: [PATCH 60/61] =?UTF-8?q?=E5=BA=8F=E5=88=97=E5=8C=96=E3=80=81?= =?UTF-8?q?=E5=8F=8D=E5=BA=8F=E5=88=97=E5=8C=96=E6=A0=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../study/demo/datastructure/tree/LinkBinTree.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java b/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java index a115304..ce3c9e4 100644 --- a/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java +++ b/src/main/java/com/algorithm/study/demo/datastructure/tree/LinkBinTree.java @@ -573,12 +573,10 @@ public static void main(String[] args) { System.out.println("-----------------------------"); // linkBinTree.divOrderTraverse();//层次遍历 // linkBinTree.levelOrder(); - //序列化树 + //序列化、反序列化树 System.out.println("-----------------------------"); - linkBinTree.serialize(); - String abc = "abc"; - abc = abc.substring(1, abc.length() - 1); - System.out.println(abc); + TreeNode deserializeTree = linkBinTree.deserialize(linkBinTree.serialize()); + linkBinTree.levelOrder(deserializeTree); // //前序遍历:根节点->左子树->右子树 // //中序遍历:左子树->根节点->右子树 // //后序遍历:左子树->右子树->根节点 From 64a5e955c07e65154f8cf889788b6be0dd8bc94a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8B=8B?= Date: Tue, 30 Jun 2020 20:55:33 +0800 Subject: [PATCH 61/61] =?UTF-8?q?=E7=A4=BC=E7=89=A9=E7=9A=84=E6=9C=80?= =?UTF-8?q?=E5=A4=A7=E4=BB=B7=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../demo/algorithm/leetcode/Solution27.java | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution27.java diff --git a/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution27.java b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution27.java new file mode 100644 index 0000000..1deae7f --- /dev/null +++ b/src/main/java/com/algorithm/study/demo/algorithm/leetcode/Solution27.java @@ -0,0 +1,67 @@ +package com.algorithm.study.demo.algorithm.leetcode; + +/** + * @author xun2.liu + * @title: Solution27 + * @projectName algorithm-study + * @description: 在一个 m*n 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于 0)。 + * 你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格、直到到达棋盘的右下角。 + * 给定一个棋盘及其上面的礼物的价值,请计算你最多能拿到多少价值的礼物? + + * 示例 1: + * + * 输入: + * [ + *   [1,3,1], + *   [1,5,1], + *   [4,2,1] + * ] + * 输出: 12 + * 解释: 路径 1→3→5→2→1 可以拿到最多价值的礼物 + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/li-wu-de-zui-da-jie-zhi-lcof + * @date 2020/6/30 20:32 + */ +public class Solution27 { + + public static int maxValue(int[][] grid) { + int row=grid.length; + int col=grid[0].length; + int[][] db=new int[row+1][col+1]; + for (int i=1;i<=row;i++){ + for (int j=1;j<=col;j++){ + db[i][j]=Math.max(db[i-1][j],db[i][j-1])+grid[i-1][j-1]; + } + } + return db[row][col]; + } + /** + * 设 f(i, j) 为从棋盘左上角走至单元格 (i ,j)的礼物最大累计价值,易得到以下递推关系:f(i,j) + * 等于 f(i,j-1) 和 f(i-1,j) 中的较大值加上当前单元格礼物价值 grid(i,j) + * f(i,j)=max[f(i,j−1),f(i−1,j)]+grid(i,j) + */ + public static int maxValue2(int[][] grid) { + int m = grid.length, n = grid[0].length; + for(int i = 0; i < m; i++) { + for(int j = 0; j < n; j++) { + if(i == 0 && j == 0) { + continue; + } + if(i == 0) { + grid[i][j] += grid[i][j - 1] ; + } else if(j == 0) { + grid[i][j] += grid[i - 1][j]; + } else { + grid[i][j] += Math.max(grid[i][j - 1], grid[i - 1][j]); + } + } + } + return grid[m - 1][n - 1]; + } + public static void main(String[] args) { + int[][] dd={{1,3,1},{1,5,1},{4,2,1}}; + + int i = maxValue(dd); + System.out.println(i); + } +}