Leetcode:414. 第三大的数
程序员文章站
2022-03-07 19:43:49
...
题目描述:
问题解答:
1.数组扩容法(此方法比较慢)
class Solution {
public int thirdMax(int[] nums) {
int[] newnums=new int[0];
for(int i=0;i<nums.length;i++) {
boolean flag=zhuangtai(nums[i],newnums);//定义状态
if(flag) {//如果数字在新数组中不存在,就加进去。
newnums=Arrays.copyOf(newnums, newnums.length+1);
newnums[newnums.length-1]=nums[i];
}
}
Arrays.sort(newnums);//对新数组排序
if(newnums.length<3) {
return newnums[newnums.length-1];
}else {
return newnums[newnums.length-3];
}
}
//判断原来的数字是否在新数组中。
private boolean zhuangtai(int num, int[] newnums) {
// TODO Auto-generated method stub
for(int i=0;i<newnums.length;i++) {
if(num==newnums[i]) {
return false;
}
}
return true;
}
}
set集合去重法1:
class Solution {
public int thirdMax(int[] nums) {
Integer max1 = null;
Integer max2 = null;
Integer max3 = null;
Set<Integer> set=new HashSet <>();
for(int i=0;i<nums.length;i++){
set.add(nums[i]); //存入Set无重复
}
for (Integer x : set) {
/*
if (x.equals(max1) || x.equals(max2) || x.equals(max3)) {
continue;
}*/
if ((max1 == null) || x > max1) {
max3 = max2;
max2 = max1;
max1 = x;
}
else if ((max2 == null) || x > max2) {
max3 = max2;
max2 = x;
}
else if ((max3 == null) || x > max3) {
max3 = x;
}
}
if (max3 == null) {
return max1;
}else {
return max3;
}
}
}
set去重法2:
class Solution {
public int thirdMax(int[] nums) {
Set<Integer>set=new LinkedHashSet<Integer>(); //新建Set
Arrays.sort(nums);//升序排列
for(int i=0;i<nums.length;i++){
set.add(nums[i]); //存入Set无重复
}
int nums1[]=new int[set.size()];
Iterator<Integer> it=set.iterator();
while (it.hasNext()) {
for(int i=0;i<set.size();i++){
nums1[i]=it.next();
}
} //读出输入到nums1[]数组中
if(nums1.length<3){return nums1[nums1.length-1];}
return nums1[nums1.length-3];
}
}
推荐阅读
-
#leetcode刷题之路16-最接近的三数之和
-
#leetcode刷题之路36-有效的数独
-
leetcode1193. 每月交易 I 编写一个 sql 查询来查找每个月和每个国家/地区的事务数及其总金额、已批准的事务数及其总金额。
-
leetcode 576. 出界的路径数
-
Leetcode 576. 出界的路径数
-
LeetCode 出界的路径数(动态规划)
-
[leetcode]16. 最接近的三数之和
-
leetcode:求两数之和,给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
-
LeetCode1.两数之和:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,返回数组下标。假设每种输入只对应一个答案。但数组中同一个元素不能使用两遍
-
LeetCode 探索 初级算法 数组 第十题:有效的数独