算法题中可以使用的一些方法
Math.max()
int max = Math.max(1,3,5,7);
返回一组数中的最大值
int max = Math.max(max,nums[j])
比较max和nums[j]的大小并将值赋给max
注意:
- max是Math的静态方法,使用时不应该创建实例的方法使用,并且Math不是构造函数 ,使用时应该
Math.max
- 如果没有参数,则结果为
Infinity
- 如果有任一参数不能被转换为数值,则结果为
NaN
Arrays.sort()
sort方法是Arrays类的静态方法,在需要对数组进行排序时,非常的好用
Arrays.sort(nums)
对于数值nums进行从小到大的排序
Arrays.sort(int[] a, int fromIndex, int toIndex)
对数组进行部分升序排序,对于数组下标为从fromIndex到toIndex-1元素进行排序,范围是左开右闭
Arrays.sort(int[] a, int fromIndex, int toIndex, Collections.reverseOrder())
对数组进行部分降序排序,也是遵循左开右闭的规则
swap()
swap(nums[i],nums[j])
交换nums[i] 和nums[j]位置
相当于
int temp = nums[i];
nums[j] = nums[i];
nums[i] = temp;
charAt()
charAt()方法用于返回索引出的字符。索引范围从0到length()-1
实例
public class Test{
public static void main(String[] args) {
String s = "www.runoob.com";
char result = s.charAt(6);
System.out.println(result);
}
}
注意:
需要定义一个char类型的变量来接收,而不是String类型
JSON.stringify()
用于将对象转换成string的字符串
JSON.parse()
字符串转换成对象
int和string类型互转
int 类型转换成string类型
1、使用num+””
int num=100;
string str1 = num+"";
2、String.valueOf()
String str2 = String.valueOf(num);
3、转化成包装类Integer,再转换成String
Integer integer = new Integer(num);
String str3 = integer.toString();
System.out.println(str3);
4、直接使用Integer.toString()
String str4 = Integer.toString(num);
System.out.println(str4);
String类型转化成int类型
1、Integer.parseInt方法,返回类型是int
int num1 = Integer.parseInt(str);
2、Integer.valueOf()方法,返回类型也是int
int num2 = Integer.valueOf(str);