zoukankan      html  css  js  c++  java
  • lintcode:两个数组的交

    题目

    返回两个数组的交

    样例

    nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2].

    解题

    排序后,两指针找相等元素,注意要去除相同的元素

    public class Solution {
        /**
         * @param nums1 an integer array
         * @param nums2 an integer array
         * @return an integer array
         */
        public int[] intersection(int[] nums1, int[] nums2) {
            // Write your code here
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            ArrayList<Integer> A = new ArrayList<Integer>();
            int i=0;
            int j=0;
            while(i<nums1.length && j<nums2.length ){
                if(nums1[i] == nums2[j]){
                    A.add(nums1[i]);
                    i++;
                    j++;
                    
                }else if(nums1[i] < nums2[j]){
                    i++;
                }else{
                    j++;
                }
                int tmpi = i;
                int tmpj = j;
                // 去重
                while(i+1<nums1.length && nums1[i]==nums1[i+1]) i++;
                while(j+1<nums2.length && nums2[j]==nums2[j+1]) j++;
                // 没有重复,按照上面更新的i 和 j 
                if(tmpi<nums1.length && tmpi ==i){
                    i= tmpi;
                }
                if(tmpj<nums2.length && tmpj ==j){
                    j = tmpj;
                }
            }
            int[] res = new int[A.size()];
            for( i=0;i<A.size();i++){
                res[i] = (int)A.get(i);
            }
            return res;
        }
    }

    利用HashMap

    将数组1的值唯一的保存在map中

    根据map在去重

    public class Solution {
        /**
         * @param nums1 an integer array
         * @param nums2 an integer array
         * @return an integer array
         */
        public int[] intersection(int[] nums1, int[] nums2) {
            // Write your code here
            HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
            
            for(int i =0;i<nums1.length;i++){
                if(!map.containsKey(nums1[i])){ // 唯一映射
                    map.put(nums1[i],1);
                }
            }
            ArrayList<Integer> A = new ArrayList<Integer>();
            for(int i=0;i<nums2.length;i++){
                if(map.containsKey(nums2[i])){ // 相同元素
                    A.add(nums2[i]);
                    map.remove(nums2[i]); // 去除相同元素
                }
            }
            int[] res = new int[A.size()];
            for(int i=0;i<A.size();i++){ // 保存到数组中
                res[i] = A.get(i);
            }
            return res;
        }
    }
  • 相关阅读:
    xposed的基本使用
    scrapy发送邮件
    Image Pipeline
    javax.validation.ConstraintViolationException---Hibernate后台实体校验
    oracle中lead和lag函数 (转载)
    oracle中根据当前记录查询前一条和后一条记录
    物化视图知识了解(转载)
    10个线程同步处理1000行消息
    SQL语句执行效率及分析(note)
    js对文本框特殊字符串过滤
  • 原文地址:https://www.cnblogs.com/bbbblog/p/5648988.html
Copyright © 2011-2022 走看看