栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

笔记:java刷算法题时可以用到的一些高效函数

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

笔记:java刷算法题时可以用到的一些高效函数

一些高效函数笔记
  • int[] ans = new int[n * 2];
  • int[] ans = Arrays.copyOf(nums, n*2);
  • System.arrayCopy
  • str.charAt(index)
  • 关于StringBuilder
  • Math里常用
  • 位运算
  • substring

int[] ans = new int[n * 2];

开新的数组

int[] ans = Arrays.copyOf(nums, n*2);

Arrays的copyOf()方法传回的数组是新的数组对象,改变传回数组中的元素值,不会影响原来的数组。

copyOf()的第二个自变量指定要建立的新数组长度,如果新数组的长度超过原数组的长度,则保留数组默认值

int[] arr1 = {1, 2, 3, 4, 5}; 
int[] arr2 = Arrays.copyOf(arr1, 5);//1,2,3,4,5
int[] arr3 = Arrays.copyOf(arr1, 10);//1,2,3,4,5,0,0,0,0,0
System.arrayCopy

arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
代码解释:
Object src : 原数组
int srcPos : 从元数据的起始位置开始
Object dest : 目标数组
int destPos : 目标数组的开始起始位置
int length : 要copy的数组的长度

//nums=1,2,3 ans=5,4,3,2,1
System.arraycopy(nums, 0, ans, 1, 3);//ans=5,1,2,3,1

str.charAt(index)

返回指定位置的字符,如str=“hello”,str.charAt(1)则为‘e’

关于StringBuilder

StringBuilder strB = new StringBuilder();

strB.append(“123”)/append(‘c’)//字符串连接

strB.deleteCharAt(1)//删除下标为1字符

strB.delete(3,5);删除下标从3到5的字符

Math里常用

Math.abs(x) 函数返回指定数字 “x“ 的绝对值

Math.max(a,b,c)函数返回一组数中的最大值。

位运算

左移( << )、右移(>>)、无符号右移( >>> )、位与( & )、位或( | )、位异或( ^ )、位非( ~ )

(5 & 3);//结果为1
(5 | 3);//结果为7
(5 ^ 3);//结果为6
(~5);//结果为-6
substring

substring(int beginIndex, int endIndex);
Str.substring(4);//str="This is text"→Str.substring(4)输出is text
Str.substring(4, 10) ;//str="This is text"→.substring(4, 10) 输出 is te

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/287399.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号