Array 数组类型题目笔记

Posted 毛线刷题笔记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Array 数组类型题目笔记相关的知识,希望对你有一定的参考价值。

将小数组归并到大数组里

Merge Sorted Array

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Example

A = [1, 2, 3, empty, empty], B = [4, 5]

After merge, A will be filled as [1, 2, 3, 4, 5]

 

2点需要注意的:

  1. inplace merge,从后往前走

  2. 3个while 循环的控制条件  

     1.  a != null && b != null

     2.  a != null

     3. b != null

    看似简单,反正我没写出来

class Solution {
    public void mergeSortedArray(int[] A, int m, int[] B, int n) {
        // write your code here
        int total = m + n - 1;
        int index1 = m - 1;
        int index2 = n - 1;
        while (index1 >= 0 && index2 >= 0) {
            if (A[index1] >= B[index2]) {
                A[total--] = A[index1--];
            } else {
                A[total--] = B[index2--];
            }
        }
        
        while (index2 >= 0) {
            A[total--] = B[index2--];
        }
        while (index1 >= 0) {
            A[total--] = A[index1--];
        }
    }
}
mergeSortedArray

---------------------------------分割线-----------------------------------

两个数组的交

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2].

方法1: hashset 为了去重,果然需要2个set

另外,为了把第二个set里的结果转化为数组,还需要第三个for循环

Time = O(n).
Space = O(n).

 1 public class Solution {
 2     public int[] intersection(int[] nums1, int[] nums2) {
 3         HashSet<Integer> set1 = new HashSet<Integer>();
 4         for(int i: nums1){
 5             set1.add(i);
 6         }
 7  
 8          HashSet<Integer> set2 = new HashSet<Integer>();
 9          for(int i: nums2){
10          if(set1.contains(i)){
11             set2.add(i);
12             }
13         }
14  
15         int[] result = new int[set2.size()];
16         int i = 0;
17         for(int n: set2){
18             result[i++] = n;
19         }
20         return result;
21         }
22 }
intersection

方法2: sort+ 2个指针

我们还可以使用两个指针来做,先给两个数组排序,然后用两个指针分别指向两个数组的开头,然后比较两个数组的大小,把小的数字的指针向后移,如果两个指针指的数字相等,那么看结果res是否为空,如果为空或者是最后一个数字和当前数字不等的话,将该数字加入结果res中,参见代码如下:

public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0) {
            return nums1;
        }
        if (nums2 == null || nums2.length == 0) {
            return nums2;
        }
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i, j;
        int size1 = nums1.length; 
        int size2 = nums2.length;
        ArrayList<Integer> res = new ArrayList<Integer>();

        for (i = 0, j = 0 ; i < size1 && j < size2;) {
            if (nums1[i] == nums2[j]) {
                if ((!res.isEmpty() && nums1[i] != res.get(res.size() - 1)) || res.isEmpty()) {
                    res.add(nums1[i]);
                }
                i++;
                j++;
            } else if (nums1[i] > nums2[j]) {
                j++;
            } else {
                i++;
            }
        }
        int[] result = new int[res.size()];
        i = 0;
        for (int temp : res) {
            result[i++] = temp;
        }
        return result;
    }
}
View Code

方法3: sort 2个array 然后遍历nums1,用binary search 来查找

Arrays.binarySearch(nums2, nums1[i]))    666还能这么玩

public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0) {
            return nums1;
        }
        if (nums2 == null || nums2.length == 0) {
            return nums2;
        }
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int size1 = nums1.length; 
        ArrayList<Integer> res = new ArrayList<Integer>();

        for (int i = 0; i < size1; i++) {
            if (i == 0 || nums1[i] != nums1[i - 1]) {
                if ((Arrays.binarySearch(nums2, nums1[i])) > -1) {
                    res.add(nums1[i]);
                }
            }
        }
        
        
        int[] result = new int[res.size()];
        int i = 0;
        for (int temp : res) {
            result[i++] = temp;
        }
        return result;
    }
}
intersection

---------------------------------分割线-----------------------------------

 快速排序系列 http://www.cnblogs.com/jiangchen/p/5935651.html

 

---------------------------------分割线-----------------------------------

 股票问题,prefix sum运用,序列型动态规划 详见

http://www.cnblogs.com/jiangchen/p/5820378.html

---------------------------------分割线-----------------------------------

 subarray 问题

动态规划部分 见 

http://www.cnblogs.com/jiangchen/p/5820378.html

 

Subarray Sum

Given an integer array, find a subarray where the sum of numbers is zero. Your code should return the index of the first number and the index of the last number.

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A list of integers includes the index of the first number 
     *          and the index of the last number
     */
    public ArrayList<Integer> subarraySum(int[] nums) {
        // write your code here
        
        int firstIndex = 0, sum = 0; 
        while (firstIndex < nums.length) {
            sum = 0;
            for (int i = firstIndex; i < nums.length ; i++) {
                sum += nums[i];
                if (sum == 0) {
                    ArrayList<Integer> result = new ArrayList<Integer>();
                    result.add(firstIndex);
                    result.add(i);
                    return result;
                }
            }
            firstIndex++;
        } 
        return null;
    }
}
subarraySum

 

Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn\'t one, return 0 instead.

For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

从左往右遍历第一个起始位置,注意,当起始位置向右边移动一个位置的时候,终止位置从上个循环的终止位置开始,避免了重复计算!

public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        // write your code here
        int j = 0, i = 0;
        int sum =0;
        int ans = Integer.MAX_VALUE;
        for(i = 0; i < nums.length; i++) {
            while(j < nums.length && sum < s ) {
                sum += nums[j];
                j ++;
            }
            if(sum >=s)
                ans = Math.min(ans, j - i  );
            sum -= nums[i];
        }
        if(ans == Integer.MAX_VALUE)
            ans = 0;
        return ans;
    }
}
minSubArrayLen

 Subarray Sum Closest

Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number.

Example

Given [-3, 1, 1, -3, 5], return [0, 2][1, 3],[1, 1][2, 2] or [0, 4].

那个-1 是因为,把前i个数转换为他的index

最后+1 是因为取2个presum中间部分,其实部分为res[0]的后一个点开始所以要+1

class Pairs {
        int sum;
        int index;
        public Pairs (int s, int i) {
            this.sum = s;
            this.index =i;
        }
    
}


public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A list of integers includes the index of the first number 
     *          and the index of the last number
     */
    private static Comparator<Pairs> SumComparator = new Comparator<Pairs>() {
        public int compare(Pairs a, Pairs b) {
            return a.sum - b.sum;
        }
    };
    public int[] subarraySumClosest(int[] nums) {
        // write your code here
        
       
       

        
        
        if (nums == null || nums.length == 0) {
            return new int[]{0, 0};
        }
        int len = nums.length;
        if (len == 1) {
            return new int[]{0, 0};
        }
        PriorityQueue<Pairs> queue = new PriorityQueue<Pairs>(nums.length, SumComparator);
        
        
        int preSum = 0;
        queue.offer(new Pairs(0,0));
        for (int i = 1; i <= len; i++) {
            preSum += nums[i - 1];
            Pairs temp = new Pairs(preSum, i);
            queue.offer(temp);
        }
        
        int[] res = new int[2];
        int diff = Integer.MAX_VALUE;
        for (int i = 0; i < len - 1; i++) {
            Pairs temp = queue.poll();
            //System.out.println("debug" + queue.peek().sum + "   " + temp.sum );
            if (queue.peek().sum - temp.sum < diff) {
                
                diff = queue.peek().sum - temp.sum;
                res[0] = temp.index - 1;
                res[1] = queue.peek().index - 1;
                //this -1 means from the first index to actually index
            }
        }

        Arrays.sort(res);
        //this add means from the index res[0] but not include res[0]
        res[0]++;
        return res;
    }
}
View Code

 

 

 

以上是关于Array 数组类型题目笔记的主要内容,如果未能解决你的问题,请参考以下文章

Swift学习笔记之---Array数组

Swift学习笔记之---Array数组

Swift学习笔记之---Array数组

javascript常用代码片段

算法通关手册 刷题笔记2 数组排序之冒泡排序选择排序

NumPy学习笔记:3更加复杂的数组