0
点赞
收藏
分享

微信扫一扫

LeetCode217. 存在重复元素&&53. 最大子数组和

覃榜言 2022-01-27 阅读 53

LeetCode217. 存在重复元素(2022.1.27第一题)

LeetCode217
方法一:将数组中每个元素插入到哈希表中

class Solution {
 
	 public boolean containsDuplicate(int[] nums) {
	        HashSet<Integer> set = new HashSet<Integer>();
	        for(int x : nums) {
	        	if(!set.add(x)) {
	        		return true; 
	        	}
	        }
	        return false;

	 }
   
}

方法二:在对数字从小到大排序之后,数组的重复元素一定出现在相邻位置中。因此,我们可以扫描已排序的数组,每次判断相邻的两个元素是否相等,如果相等则说明存在重复的元素。

class Solution {
    public boolean containsDuplicate(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = 0; i < n - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                return true;
            }
        }
        return false;
    }
}

LeetCode53. 最大子数组和(2022.1.27第二题)

LeetCode 第53题

class Solution {
    public int maxSubArray(int[] nums) {
    	int sum=0;//存放当前最大整数
    	int ans=nums[0];//存放最终结果
    	for (int i = 0; i < nums.length; i++) {
			if(sum>0) {
				sum+=nums[i];
			}else {
				sum=nums[i];
			}
			ans=Math.max(sum, ans);
		}
    	return ans;
    }
}
举报

相关推荐

0 条评论