我是靠谱客的博主 酷酷台灯,这篇文章主要介绍java 力扣算法题目介绍:(数组的循环遍历比较,绝对值函数的使用)题目:(考察数组的循环遍历求和,返回数组,接收数组,打印数组)题目(回文数,反转算法) ,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution { public static void main(String[] args) { int nums[] = {5,4,3,2,1}; int res = countKDifference(nums,4); System.out.println(res); } public static int countKDifference(int[] nums, int k) { int res = 0; int n = nums.length; for(int i=0;i<n;i++){ for(int j=1;j<n;j++){ if(Math.abs(nums[i]-nums[j]) == k){ res++; } } } return res; } }

题目介绍:(数组的循环遍历比较,绝对值函数的使用)

给你一个整数数组 nums 和一个整数 k ,请你返回数对 (i, j) 的数目,满足 i < j 且 |nums[i] - nums[j]| == k 。

|x| 的值定义为:

如果 x >= 0 ,那么值为 x 。
如果 x < 0 ,那么值为 -x 。

知识点:

API的学习:

        1、自动获取数组的长度,nums.length;

        2、求平均值的函数(Math.abs())

 

 

题目:(考察数组的循环遍历求和,返回数组,接收数组,打印数组)

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.Arrays; public class Solution { public static void main(String[] args) { int nums[] = {5,4,3,2,1}; int [] res = twoSum(nums,4); for(int i=0;i<res.length;i++){ System.out.println(res[i]); } System.out.println(Arrays.toString(res)); } public static int[] twoSum(int[] nums, int target) { int res = 0; int n = nums.length; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(nums[i]+nums[j] == target){ return new int[]{i,j}; } } } return new int[0]; } }

 知识点:

        1、返回值是数组的小标:new int[]{i,j};

        2、接收数组。int []res = ....;

        3、打印数组使用Array 的API的tostring;或者使用for循环打印;

题目(回文数,反转算法) 

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。

回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。

算法逻辑:

1、首先不可能是回文数的情况:

        1、负数

        2、个位是0,或者末尾是0的情况。        

2、其次就是考虑反转后半部分的数字:

        1、对于数字 1221,如果执行 1221 % 10,我们将得到最后一位数字 1,要得到倒数第二位数字,我们可以先通过除以 10 把最后一位数字从 1221 中移除,1221 / 10 = 122,再求出上一步结果除以 10 的余数,122 % 10 = 2,就可以得到倒数第二位数字。如果我们把最后一位数字乘以 10,再加上倒数第二位数字,1 * 10 + 2 = 12,就得到了我们想要的反转后的数字。如果继续这个过程,我们将得到更多位数的反转数字。

3、我们如何知道反转数字的位数已经达到原始数字位数的一半?

        由于整个过程我们不断将原始数字除以 10,然后给反转后的数字乘上 10,所以,当原始数字小于或等于反转后的数字时,就意味着我们已经处理了一半位数的数字了。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.Arrays; public class Solution { public static void main(String[] args) { System.out.println(isPalindrome(1221)); } public static boolean isPalindrome(int x) { //情况1 if(x<0 ||(x%10 == 0 && x!=0)){ return false; } int res = 0; while(x > res){ res = res *10 + x % 10; x /=10; } // 当数字长度为奇数时,我们可以通过 revertedNumber/10 去除处于中位的数字。 // 例如,当输入为 12321 时,在 while 循环的末尾我们可以得到 x = 12,revertedNumber = 123, // 由于处于中位的数字不影响回文(它总是与自己相等),所以我们可以简单地将其去除。 return x == res || x == res/10; } }

最后

以上就是酷酷台灯最近收集整理的关于java 力扣算法题目介绍:(数组的循环遍历比较,绝对值函数的使用)题目:(考察数组的循环遍历求和,返回数组,接收数组,打印数组)题目(回文数,反转算法) 的全部内容,更多相关java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(72)

评论列表共有 0 条评论

立即
投稿
返回
顶部