提交 eb054be5 编写于 作者: 梦境迷离's avatar 梦境迷离

fix code smell

please use english commit message
上级 6813cf71
# This workflow will build a Java project with Gradle
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle
name: Build jvm language module
name: Build jvm language modules
on:
push:
......
name: Build rust language module
name: Build rust language modules
on:
push:
......
......@@ -46,6 +46,7 @@ and can freely submit the code (unlimited language, get more information from [i
- Rust 1.4+
- Kotlin 1.3+
- C++ 11
- Ruby 2.5+
### Contributors
......
#!/bin/bash
# set -v
# if donnot have all environments, format only your module which edit
enable_language=("java","rust","scala","python","c++","kotlin")
enable_language=("java","rust","scala","python","c++","kotlin","ruby")
root_path=`pwd`
# auto compile java and scala
......@@ -31,6 +31,8 @@ do
"python")
echo "############ [ TODO ]";;
"c++")
echo "############ [ TODO ]";;
"ruby")
echo "############ [ TODO ]";;
*)
echo "| exclude $sub_module";;
......
......@@ -11,9 +11,9 @@ public class TestJava3 {
public static void main(String[] args) {
A a = new A();
System.out.println(a instanceof B); // true a与父类
System.out.println(a instanceof C); // true a与父接口
System.out.println(a instanceof D); // false a与子类
System.out.println(a instanceof B); // true a与父类 lgtm [java/useless-type-test]
System.out.println(a instanceof C); // true a与父接口 lgtm [java/useless-type-test]
System.out.println(a instanceof D); // false a与子类 lgtm [java/useless-type-test]
}
}
......
......@@ -76,8 +76,7 @@ public class ConnectionPoolTest {
if (connection != null) {
try {
connection.createStatement();
// lgtm [java/database-resource-leak
connection.createStatement(); // lgtm [java/database-resource-leak
connection.commit();
} catch (SQLException e) {
// TODO 自动生成的 catch 块
......
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
public class Base implements Cloneable {
@Override
public Object clone() {
Base o = null;
try {
o = (Base) super.clone();
System.out.println("正在调用基类的拷贝"); // 1
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
public static void main(String[] args) {
@SuppressWarnings("unused")
Base base = new Children();
// Object object = base.clone();// 打印1,2
Children c1 = new Children();
@SuppressWarnings("unused")
Children c2 = new Children();
c2 = c1;
}
}
class Children extends Base {
@Override
public Object clone() {
Children o = null;
o = (Children) super.clone();
System.out.println("正在调用子类的拷贝"); // 2
return o;
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import java.util.List;
/**
* @author 梦境迷离
* @time 2018-11-29
*/
public class JavaIntersectionList {
public static void main(String[] args) {
List<String> list1 = new ArrayList();
list1.add("1111");
list1.add("2222");
list1.add("3333");
List<String> list2 = new ArrayList();
list2.add("3333");
list2.add("4444");
list2.add("5555");
// 交集
// List<String> intersection = list1.stream().filter(item ->
// list2.contains(item)).collect(toList());
// setA - (setA - setB) 需要实现equals ,暂时没有想到直接lambda filter不需要equals的实现方法
list1.retainAll(list2);
System.out.println("---得到交集 intersection---");
list1.parallelStream().forEach(System.out::println);
// 差集 (list1 - list2)
List<String> reduce1 =
list1.stream().filter(item -> !list2.contains(item)).collect(toList());
System.out.println("---得到差集 reduce1 (list1 - list2)---");
reduce1.parallelStream().forEach(System.out::println);
// 差集 (list2 - list1)
List<String> reduce2 =
list2.stream().filter(item -> !list1.contains(item)).collect(toList());
System.out.println("---得到差集 reduce2 (list2 - list1)---");
reduce2.parallelStream().forEach(System.out::println);
// 并集
List<String> listAll = list1.parallelStream().collect(toList());
List<String> listAll2 = list2.parallelStream().collect(toList());
listAll.addAll(listAll2);
System.out.println("---得到并集 listAll---");
listAll.parallelStream().forEach(System.out::println);
// 去重并集
List<String> listAllDistinct = listAll.stream().distinct().collect(toList());
System.out.println("---得到去重并集 listAllDistinct---");
listAllDistinct.parallelStream().forEach(System.out::println);
System.out.println("---原来的List1---");
list1.parallelStream().forEach(System.out::println);
System.out.println("---原来的List2---");
list2.parallelStream().forEach(System.out::println);
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
import java.util.HashMap;
import java.util.Iterator;
/**
* 以下是一个基于 双向队列 + HashMap 的 LRU 算法实现,对算法的解释如下:
*
* <p>最基本的思路是当访问某个节点时,将其从原来的位置删除,并重新插入到链表头部 这样就能保证链表尾部存储的就是最近最久未使用的节点,当节点数量大于缓存最大空间时就删除链表尾部的节点。
* 为了使删除操作时间复杂度为 O(1),那么就不能采用遍历的方式找到某个节点。HashMap 存储这 Key 到节点的映射,通过 Key 就能以 O(1) 的时间得到节点,然后再以 O(1)
* 的时间将其从双向队列中删除。
*
* @author 梦境迷离
* @version v1.0
* @time 2018年8月1日
*/
public class LRU<K, V> implements Iterable<K> {
private Node head;
private Node tail;
private HashMap<K, Node> map;
private int maxSize;
private class Node {
Node pre;
Node next;
K k;
V v;
public Node(K k, V v) {
this.k = k;
this.v = v;
}
}
public LRU(int maxSize) {
this.maxSize = maxSize;
this.map = new HashMap<>(maxSize);
head = new Node(null, null);
tail = new Node(null, null);
head.next = tail;
tail.pre = head;
}
public V get(K key) {
if (!map.containsKey(key)) {
return null;
}
Node node = map.get(key);
unlink(node);
appendHead(node);
return node.v;
}
public void put(K key, V value) {
if (map.containsKey(key)) {
Node node = map.get(key);
unlink(node);
}
Node node = new Node(key, value);
map.put(key, node);
appendHead(node);
if (map.size() > maxSize) {
Node toRemove = removeTail();
map.remove(toRemove);
}
}
private void unlink(Node node) {
Node pre = node.pre;
node.pre = node.next;
node.next = pre;
}
private void appendHead(Node node) {
node.next = head.next;
head.next = node;
}
private Node removeTail() {
Node node = tail.pre;
node.pre = tail;
return node;
}
@Override
public Iterator<K> iterator() {
return new Iterator<K>() {
private Node cur = head.next;
@Override
public boolean hasNext() {
return cur != tail;
}
@Override
public K next() {
Node node = cur;
cur = cur.next;
return node.k;
}
};
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
import java.util.HashMap;
import java.util.Scanner;
/**
* @author 梦境迷离
* @time 2018年9月28日
*/
public class LRUCache {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
LRUCache l = new LRUCache(n);
int t = 0;
while (scanner.hasNext()) {
String k = scanner.nextLine() + " ";
String[] arr = k.split("\\ ");
if (arr.length == 2) {
l.put(Integer.parseInt(arr[0]), Integer.parseInt(arr[1]));
}
if (arr.length == 1) {
t = Integer.parseInt(arr[0]);
break;
}
}
Object ret = null;
if (t != 0) {
ret = l.get(t);
}
if (ret == null) {
System.out.println(-1);
} else {
System.out.println(ret);
}
}
int capacity;
HashMap<Integer, Node> map = new HashMap<Integer, Node>();
Node head = null;
Node end = null;
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if (map.containsKey(key)) {
Node n = map.get(key);
remove(n);
setHead(n);
return n.value;
}
return -1;
}
public void remove(Node n) {
if (n.pre != null) {
n.pre.next = n.next;
} else {
head = n.next;
}
if (n.next != null) {
n.next.pre = n.pre;
} else {
end = n.pre;
}
}
public void setHead(Node n) {
n.next = head;
n.pre = null;
if (head != null) head.pre = n;
head = n;
if (end == null) end = head;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
Node old = map.get(key);
old.value = value;
remove(old);
setHead(old);
} else {
Node created = new Node(key, value);
if (map.size() >= capacity) {
map.remove(end.key);
remove(end);
setHead(created);
} else {
setHead(created);
}
map.put(key, created);
}
}
}
class Node {
int key;
int value;
Node pre;
Node next;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
/** 多线程下载 和 断点续传 */
public class MuchThreadDown {
// //下载路径
private String path = null;
private String targetFilePath = "/"; // 下载文件存放目录
private int threadCount = 3; // 线程数量
/**
* 构造方法
*
* @param path 要下载文件的网络路径
* @param targetFilePath 保存下载文件的目录
* @param threadCount 开启的线程数量,默认为 3
*/
public MuchThreadDown(String path, String targetFilePath, int threadCount) {
this.path = path;
this.targetFilePath = targetFilePath;
this.threadCount = threadCount;
}
/** 下载文件 */
public void download() throws Exception {
// 连接资源
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
int code = connection.getResponseCode();
if (code == 200) {
// 获取资源大小
int connectionLength = connection.getContentLength();
System.out.println(connectionLength);
// 在本地创建一个与资源同样大小的文件来占位
RandomAccessFile randomAccessFile =
new RandomAccessFile(new File(targetFilePath, getFileName(url)), "rw");
randomAccessFile.setLength(connectionLength);
/*
* 将下载任务分配给每个线程
*/
int blockSize = connectionLength / threadCount; // 计算每个线程理论上下载的数量.
for (int threadId = 0; threadId < threadCount; threadId++) { // 为每个线程分配任务
int startIndex = threadId * blockSize; // 线程开始下载的位置
int endIndex = (threadId + 1) * blockSize - 1; // 线程结束下载的位置
if (threadId == (threadCount - 1)) { // 如果是最后一个线程,将剩下的文件全部交给这个线程完成
endIndex = connectionLength - 1;
}
new DownloadThread(threadId, startIndex, endIndex).start(); // 开启线程下载
}
randomAccessFile.close();
}
}
// 下载的线程
private class DownloadThread extends Thread {
private int threadId;
private int startIndex;
private int endIndex;
public DownloadThread(int threadId, int startIndex, int endIndex) {
this.threadId = threadId;
this.startIndex = startIndex;
this.endIndex = endIndex;
}
@Override
public void run() {
System.out.println("线程" + threadId + "开始下载");
try {
// 分段请求网络连接,分段将文件保存到本地.
URL url = new URL(path);
// 加载下载位置的文件 临时文件
File downThreadFile = new File(targetFilePath, "downThread_" + threadId + ".dt");
RandomAccessFile downThreadStream = null;
if (downThreadFile.exists()) { // 如果文件存在
downThreadStream = new RandomAccessFile(downThreadFile, "rwd");
String startIndex_str = downThreadStream.readLine();
if (null == startIndex_str || "".equals(startIndex_str)) { // 网友
// imonHu
this.startIndex = Integer.parseInt(startIndex_str);
} else {
this.startIndex = Integer.parseInt(startIndex_str) - 1; // 设置下载起点
}
} else {
downThreadStream = new RandomAccessFile(downThreadFile, "rwd");
}
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
// 设置分段下载的头信息。 Range:做分段数据请求用的。格式: Range bytes=0-1024 或者
// bytes:0-1024
connection.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
System.out.println(
"线程_" + threadId + "的下载起点是 " + startIndex + " 下载终点是: " + endIndex);
if (connection.getResponseCode() == 206) { // 200:请求全部资源成功,
// 206代表部分资源请求成功
InputStream inputStream = connection.getInputStream(); // 获取流
RandomAccessFile randomAccessFile =
new RandomAccessFile(
new File(targetFilePath, getFileName(url)),
"rw"); // 获取前面已创建的文件.
randomAccessFile.seek(startIndex); // 文件写入的开始位置.
/*
* 将网络流中的文件写入本地
*/
byte[] buffer = new byte[1024];
int length = -1;
int total = 0; // 记录本次下载文件的大小
while ((length = inputStream.read(buffer)) > 0) {
randomAccessFile.write(buffer, 0, length);
total += length;
/*
* 将当前现在到的位置保存到文件中
*/
downThreadStream.seek(0);
downThreadStream.write((startIndex + total + "").getBytes("UTF-8"));
}
downThreadStream.close();
inputStream.close();
randomAccessFile.close();
cleanTemp(downThreadFile); // 删除临时文件
System.out.println("线程" + threadId + "下载完毕");
} else {
System.out.println("响应码是" + connection.getResponseCode() + ". 服务器不支持多线程下载");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 删除线程产生的临时文件
private synchronized void cleanTemp(File file) {
file.delete();
}
// 获取下载文件的名称
private String getFileName(URL url) {
String filename = url.getFile();
String[] s = filename.split("\\?");
String s2 = s[0].substring(s[0].lastIndexOf("."));
System.out.println("后缀名:" + s2);
return filename.substring(filename.lastIndexOf("sourceid") + 9) + s2;
}
public static void main(String[] args) {
try {
new MuchThreadDown(null, null, 3).download();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
/**
* @author 梦境迷离
* @time 2018-09-08
*/
public class TestJava {
public static void main(String[] args) {
String a = "A";
String b = "B";
StringBuffer sa = new StringBuffer();
sa.append(a);
change(sa, b);
System.out.println(sa.toString()); // AB
}
public static void change(StringBuffer sa, String b) {
sa.append(b);
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
/**
* 语法测试
*
* @author 梦境迷离
* @time 2018-09-28
*/
public class TestJava1 {
public static void main(String[] args) {
BB B = new BB();
// 输出
// static A
// static B
// A
// B
}
}
class AA {
static {
System.out.println("static A");
}
AA() {
System.out.println("A");
}
}
class BB extends AA {
static {
System.out.println("static B");
}
BB() {
System.out.println("B");
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
/**
* 语法测试
*
* @author 梦境迷离
* @time 2018-09-28
*/
public class TestJava2 {
static String result = "";
public static void main(String[] args) {
test(1);
System.out.println(result);
}
public static void test(int n) {
try {
if (n == 0) {
throw new Exception();
}
} catch (Exception e) {
result += "CATCH" + "\n";
} finally {
result += "FINALLY" + "\n"; // 有return 时,n=1输出FINALLY n=0输出CATCH FINALLY
// return;// 有return 时 result += "END" + "\n"; 报错
}
result += "END" + "\n"; // 无return时,n=0输出 CATCH FINALLY END,n=1输出 FINALLY END
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
/**
* 测试语法
*
* @author 梦境迷离
* @time 2018-09-08
*/
public class TestJava3 {
public static void main(String[] args) {
A a = new A();
System.out.println(a instanceof B); // true a与父类
//lgtm [java/useless-type-test
System.out.println(a instanceof C); // true a与父接口
//lgtm [java/useless-type-test
System.out.println(a instanceof D); // false a与子类
}
}
interface C {}
abstract class B implements C {}
class A extends B {}
class D extends A {}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
/**
* 测试
*
* @author 梦境迷离
* @time 2018-09-08
*/
public class TestJava5 {
public static void main(String[] args) {
int s = ~10;
System.out.println(s);
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
import java.util.List;
public class TestJava6 {
public static void main(String[] args) {}
public void inspect(List<?> list) {
for (Object object : list) {
System.out.println(object);
}
// list.add(1);
// 向未知集合中添加对象不是类型安全的,这会导致编译错误,唯一例外的是null jdk1.5以后可以使用指定索引的添加
}
// public void test() {
// List<String> strs = new ArrayList<String>();
// inspect(strs);//编译错误
// }
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
/**
* 测试
*
* @author 梦境迷离
* @time 2018-08-15
*/
public class TestJava7 extends Thread {
public static void main(String[] args) {
TestJava7 t = new TestJava7();
TestJava7 s = new TestJava7();
t.start();
System.out.println("one.");
s.start();
System.out.println("two.");
}
public void run() {
System.out.println("Thread");
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
import java.util.ArrayList;
import java.util.List;
/**
* 根据注释得知:
*
* <p>1,该方法返回的是父list的一个视图,从fromIndex(包含),到toIndex(不包含)。fromIndex=toIndex 表示子list为空
*
* <p>2,父子list做的非结构性修改(non-structural
* changes)都会影响到彼此:所谓的“非结构性修改”,是指不涉及到list的大小改变的修改。相反,结构性修改,指改变了list大小的修改。
*
* <p>3,对于结构性修改,子list的所有操作都会反映到父list上。但父list的修改将会导致返回的子list失效。
*
* <p>4,tips:如何删除list中的某段数据: list.subList(from, to).clear();
*
* @author 梦境迷离
* @time 2018-08-15
*/
public class TestJava8 {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("a");
// 使用构造器创建一个包含list的列表list1
List<String> list1 = new ArrayList<String>(list);
// 使用subList生成与list相同的列表list2
List<String> list2 = list.subList(0, list.size());
list2.add("b");
/** 可以发现,list2为list的子list,当list2发生结构性修改(list2.add("b"))后,list也发生相应改变,所以返回结果为false和true */
System.out.println(list.equals(list1));
System.out.println(list.equals(list2));
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
import java.util.ArrayList;
import java.util.List;
public class TestJava9 {
@SuppressWarnings("unused")
public static void main(String[] args) {
short s = 128;
byte b = (byte) 128;
System.out.println(s);
System.out.println(b);
String ss = "hello world";
// 替换所有包含o的字符串
String result = ss.replace("o", "");
String result2 = ss.replaceAll("o", "");
String result3 = ss.replaceFirst("o", "");
System.out.println(
"replace:" + result + "\nreplaceAll:" + result2 + "\nreplaceFirst:" + result3);
// 下列报错,点不可以赋给任何点
// ArrayList<String> list = new ArrayList<>();
// ArrayList<Object> list2 = list;
// 下列正确
// ArrayList<Object> list = new ArrayList<>();
// List<?> sList = list;
// 下列正确。点赋给范围是OK的
List<? extends Object> list3 = new ArrayList<String>();
// ? 无限制
// <? extends> 不能存,即set方法无效
// <super ?> 不能取,即get方法失效
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* H1,H2,H2_1,H3 四个线程 H1和H2,H3三个是异步的,但前三个与H4是同步关系
* 又由于H2有子线程H2_1,依赖于H2,则等价于,H1,H2_1,H3是并行,若H2_1执行之前,H2没有完成,应该阻塞,待H2完成,且H1,H2_1,H3全部完成,才可以执行H4
*
* @author 梦境迷离
* @date 21点51分
*/
public class TestJavaThread {
private static final String H1 = "H1任务";
private static final String H2 = "H2任务";
private static final String H2_1 = "H2_1任务";
private static final String H3 = "H3任务";
private static final String H4 = "H4任务";
static ThreadB taskB = new ThreadB(H2); // B同步
static Thread threadB = new Thread(taskB);
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
CallableThread taskA = new CallableThread(H1); // A异步
CallableThread taskC = new CallableThread(H3); // C异步
CallableThread taskB_1 = new CallableThread(H2_1); // B-1异步
// 依此启动线程
Future<String> futureA = executor.submit(taskA);
threadB.start();
Future<String> futureC = executor.submit(taskC);
Future<String> futureB_1 = executor.submit(taskB_1);
while (true) {
if (futureA.isDone() && futureC.isDone() && futureB_1.isDone()) {
// 保证前面四个线程已经执行了
System.out.println(H4); // 开启新的线程并执行H4即可
break;
}
}
System.out.println("finished");
}
// H1,H2_1,H3是并行的
static class CallableThread implements Callable<String> {
private String id;
public CallableThread(String id) {
this.id = id;
}
public String call() {
// 如果此时执行H2_1,前提需要保证开启H2线程,并且H2执行完成才可以继续执行本(H2_1)线程
if (H2_1.equals(this.id)) {
try {
// 不安全
threadB.join();
// 模拟时间
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(this.id);
return this.id;
}
}
// H2
static class ThreadB implements Runnable {
private String id;
public ThreadB(String id) {
this.id = id;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.id);
}
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
import java.util.Scanner;
/**
* @author 梦境迷离
* @time 2018-09-09
*/
public class TestMain1 {
public static String reverseString(String str) {
char[] chars = str.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = chars.length - 1; i >= 0; i--) {
sb.append(chars[i]);
}
return sb.toString();
}
/**
* 最大对称子串
*
* @param str
* @return
*/
public static String longestPalindrome(String str) {
String max = "";
int count = 0;
for (int i = 0; i < str.length(); i++) {
for (int j = str.length(); (j >= i) & (j - i >= max.length()); j--) {
count++;
String substr = str.substring(i, j);
int middle = 0;
if (substr.length() % 2 == 0) {
middle = substr.length() / 2;
} else {
middle = substr.length() / 2 + 1;
}
if (substr.substring(0, substr.length() / 2)
.equals(reverseString(substr.substring(middle)))) {
if (max.length() < substr.length()) {
max = substr;
}
}
}
}
return max;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
System.out.println(longestPalindrome(str));
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
import java.util.Scanner;
/**
* @author 梦境迷离
* @time 2018-09-11
*/
public class TestMain2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
boolean ret = util(n);
System.out.println(ret);
}
// 求素数
private static boolean util(int n) {
boolean ret = true;
int m = (int) Math.sqrt(n);
for (int i = 2; i < m; i++) {
if (n % i == 0) {
ret = false;
break;
}
}
return ret;
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
import java.util.Scanner;
public class TestMain3 {
/*
任意多个数字组合, 和为定值
5
1 2 3 4 5
10
4
3 1 5 9
14
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
N = input.nextInt();
nums = new int[N];
for (int i = 0; i < N; i++) nums[i] = input.nextInt();
target = input.nextInt();
dfs(0, 0);
System.out.println(flag);
input.close();
}
private static int target = 0;
private static int[] nums;
private static int N;
private static boolean flag = false;
public static void dfs(int depth, int sum) {
if (sum == target) {
flag = true;
return;
}
// if (flag == true) // 可以更快收敛
// return ;
for (int i = depth; i < N; i++) {
dfs(depth + 1, sum + nums[depth]);
dfs(depth + 1, sum);
}
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
import java.util.Scanner;
/**
* @author 梦境迷离
* @time 2018-09-17
*/
public class TestMain4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// String s = scanner.nextLine();
int n = scanner.nextInt();
int ret = utilFor2(n);
System.out.println(ret);
// String ret = util(s.trim().toCharArray(), s.length() - 1);
// System.out.println(ret);
}
/**
* 字符串反转
*
* @param str
* @param length
* @return
*/
private static String util(char[] str, int length) {
for (int i = 0; i <= length / 2; i++) {
char temp = str[i];
str[i] = str[length - i];
str[length - i] = temp;
}
return new String(str).trim();
}
/**
* 计算0~n之间含有的2的个数
*
* @param end
* @return
*/
private static int utilFor2(int end) {
int count = 0; // 统计2出现的次数的变量count
// 从开始的数字到结束的数字循环,一个一个数判断
for (int i = 0; i <= end; i++) {
int tmp = i; // 把i赋给一个临时变量tmp
// 把这个数的每一位数字用tmp%10取出,判断其是否等于2
while (tmp > 0) {
int n = tmp % 10;
if (n == 2) { // 如果这个数中有一位的数字等于2,count加1
count++;
}
tmp = tmp / 10;
}
}
return count;
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
import java.util.Scanner;
/**
* @author 梦境迷离
* @time 2018-09-28
*/
public class TestMain5 {
/**
* 跳跃
*
* @param arr
* @return
*/
public static int jump(int[] arr) {
if (arr == null || arr.length == 0) {
return 0;
}
int jump = 0;
int cur = 0;
int next = 0;
for (int i = 0; i < arr.length; i++) {
if (cur < i) {
jump++;
cur = next;
}
next = Math.max(next, i + arr[i]);
}
return jump;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine() + ",";
String[] nums = input.split(",");
int[] ns = new int[nums.length];
int k = 0;
for (String s : nums) {
ns[k++] = Integer.parseInt(s);
}
int ret = jump(ns);
System.out.println(ret);
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
import java.util.Scanner;
/**
* 只有一个数字出现了2次,求这个数
*
* @author 梦境迷离
* @time 2018-09-28
*/
public class TestMain6 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine() + ",";
String[] nums = input.split(",");
int[] ns = new int[101];
int k = 0;
for (String s : nums) {
ns[k++] = Integer.parseInt(s);
}
int ret = find(ns);
System.out.println(ret);
}
public static int find(int a[]) {
int temp = 0;
for (int i = 0; i < 101; i++) {
temp = temp ^ a[i];
}
return temp ^ 100;
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
public class TestMain7 {
private static int j;
public static void main(String[] args) {
TestMain7 many = new TestMain7();
Inc inc = many.new Inc();
Dec dec = many.new Dec();
Thread threada = null;
Thread threadb = null;
for (int i = 0; i < 5; i++) {
threada = new Thread(inc);
threada.start();
threadb = new Thread(dec);
threadb.start();
}
try {
threada.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
threadb.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(j);
}
private synchronized void inc() {
j++;
}
private synchronized void dec() {
j--;
}
class Inc implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
inc();
}
}
}
class Dec implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
dec();
}
}
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
import java.util.Scanner;
/**
* @author 梦境迷离
* @time 2018-10-09
*/
public class TestMain8 {
public static void main(String[] args) {
String s = new Scanner(System.in).nextLine();
String[] strings = s.split(":");
// BigInteger ret = new BigInteger(strings[0]).add(new BigInteger(strings[1]));
String ret = add2(strings[0], strings[1]);
System.out.println(ret);
}
/**
* 用字符串模拟两个大数相加
*
* @param n1 加数1
* @param n2 加数2
* @return 相加结果
*/
public static String add2(String n1, String n2) {
StringBuffer result = new StringBuffer();
// 1、反转字符串
n1 = new StringBuffer(n1).reverse().toString();
n2 = new StringBuffer(n2).reverse().toString();
int len1 = n1.length();
int len2 = n1.length();
int maxLen = len1 > len2 ? len1 : len2;
boolean nOverFlow = false; // 是否越界
int nTakeOver = 0; // 溢出数量
// 2.把两个字符串补齐,即短字符串的高位用0补齐
if (len1 < len2) {
for (int i = len1; i < len2; i++) {
n1 += "0";
}
} else if (len1 > len2) {
for (int i = len2; i < len1; i++) {
n2 += "0";
}
}
// 3.把两个正整数相加,一位一位的加并加上进位
for (int i = 0; i < maxLen; i++) {
int nSum = Integer.parseInt(n1.charAt(i) + "") + Integer.parseInt(n2.charAt(i) + "");
if (nSum >= 10) {
if (i == (maxLen - 1)) {
nOverFlow = true;
}
nTakeOver = 1;
result.append(nSum - 10);
} else {
nTakeOver = 0;
result.append(nSum);
}
}
// 如果溢出的话表示位增加了
if (nOverFlow) {
result.append(nTakeOver);
}
return result.reverse().toString();
}
}
/* All Contributors (C) 2020 */
package cn.edu.jxnu.other;
/**
* @author 梦境迷离
* @description
* @time 2018年3月28日
*/
public class TestStaticVar {
@SuppressWarnings("unused")
private static int count = 10;
public static void main(String[] args) {
// 笔试题,优先使用局部
int count = 0;
System.out.println(count);
// 笔试题,Date不是lang包下的,因为需要导包
}
}
......@@ -40,8 +40,7 @@ public class CalculateStringDistance {
}
}
if (pBBegin > pBEnd) {
if (pABegin > pAEnd) {
//lgtm [java/constant-comparison
if (pABegin > pAEnd) { //lgtm [java/constant-comparison
return 0;
} else {
return pAEnd - pABegin + 1;
......
......@@ -11,11 +11,6 @@ public class FibonacciDemo3 {
System.out.println(new FibonacciDemo3().jumpFloorII(10));
}
/**
* @description 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
* @param target
* @return
*/
/**
* @description 移位
* @param number
......
......@@ -47,8 +47,7 @@ public class FindTheNumber {
int hit = 0;
int hit1 = -1;
int hit2 = -1;
for (int j = 0; j < rg.length && (hit <= 2); j++) {
//lgtm [java/constant-comparison
for (int j = 0; j < rg.length && (hit <= 2); j++) { //lgtm [java/constant-comparison
// hit==2表示这个条件只能被满足两次,也就是说对于一个i,在rg数组的30个数中,
// 这个i能被其它28个数整除,而不能被其中两个数整除。
if ((i % rg[j]) != 0) {
......
......@@ -40,7 +40,7 @@ public class Main1 {
/**
* @description 数组逆转
* @param arr
* @param t
* @param begin
* @param end
* @return
......
......@@ -29,7 +29,7 @@ public class PrintMatrix {
/**
* @description 打印
* @param list
* @param arr
* @param col
*/
public void show(int[][] arr, int col) {
......
......@@ -23,7 +23,7 @@ public class ReOrderArray {
while (i < a.length && !isEven(a[i])) i++;
j = i + 1; // 从第一个偶数后面找奇数
while (j < a.length && isEven(a[j])) j++;
if (j < a.length && i < a.length) {
if (j < a.length && i < a.length) { //lgtm [java/constant-comparison]
int tmp = a[j];
for (int j2 = j - 1; j2 >= i; j2--) {
a[j2 + 1] = a[j2];
......
......@@ -171,8 +171,7 @@ object Function3 extends App {
prt(arr: _*) //OK,告诉编译器将arr的每个元素作为参数传进去,而不是将arr作为一个整体
//带名字参数,字面量/匿名函数不能使用带名参数
val su = (x: Int, y: Int) => x + y
// val suu = su(y = 1, x = 2)
val su = (x: Int, y: Int) => x + y // val suu = su(y = 1, x = 2)
def sum(x: Int, y: Int) = x + y
......
......@@ -16,10 +16,6 @@ object IOBasic {
val liness = Source.fromFile(file).getLines().toList
def main(args: Array[String]): Unit = {
// for (line <- Source.fromFile(file).getLines()) {
// println(line.length + " " + line)
// }
//格式化打印
val maxWidth = widthOfLength(longestLine)
......
......@@ -54,7 +54,6 @@ object LoopBasic {
def loopTest(list: List[Int]): Unit = {
println("函数式遍历")
//list.foreach(args => print(args + " "))
list.foreach(println)
println()
println("================================")
......
/* Licensed under Apache-2.0 @梦境迷离 */
package io.github.dreamylost
import scala.collection.mutable.HashMap
/**
* 数组的度
*
......@@ -22,28 +20,27 @@ object Leetcode_697_Array extends App {
print(findShortestSubArray(Array(1, 2, 2, 3, 1, 4, 2)))
def findShortestSubArray(nums: Array[Int]): Int = {
val map = new HashMap[Integer, Array[Int]]
import scala.collection.mutable
val map = new mutable.HashMap[Integer, Array[Int]]
//record分别记录[最大频率,最小索引,最大索引]
var record: Array[Int] = null
var maxFreq = 0
for (i <- 0 until nums.length) {
for (i <- nums.indices) {
if (!map.contains(nums(i))) {
map.put(nums(i), Array(1, i, i))
} else {
record = map.get(nums(i)).get
record = map(nums(i))
map.put(nums(i), Array(record(0) + 1, record(1), i))
}
//更新最大频率
record = map.get(nums(i)).get
record = map(nums(i))
maxFreq = math.max(maxFreq, record(0))
}
var minLen = Int.MaxValue
for (n <- nums) {
record = map.get(n).get
if (record(0) == maxFreq) {
if (record(2) - record(1) < minLen) {
minLen = record(2) - record(1) + 1
}
record = map(n)
if (record(0) == maxFreq && record(2) - record(1) < minLen) {
minLen = record(2) - record(1) + 1
}
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册