算法(存在重复元素、两数之和)

一 存在重复元素

关键代码:

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

  

思路:可以利用容器Set元素唯一 的特点,将nums[]中的元素加入,如果不可以添加说明该元素在数组中个数>=2 返回false,否则返回true

二 两数之和

关键代码:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        //指定数组长度为2
        int arr[]=new int[2];
       HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
      for(int i=0;i<nums.length;i++){
           
           if(map.containsKey(nums[i])){
                arr[0]=map.get(nums[i]);
                arr[1]=i;
           }
           
           map.put(target-nums[i],i); 
       }
   return arr;
    }
}

 思路:先使用for循环遍历数组 nums,判断map中是否存在 target-nums[i] 的 key 值,
如果存在则找到了两个值,如果不存在则将当前的 (nums[i],i) 存入 map 中,继续遍历直到找到为止

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值