Arrays Flashcards
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int e1=m-1; int e2=n-1; int curr=nums1.length-1; while(curr>=0) { if(e1 <0) { nums1[curr]=nums2[e2]; e2--; } else if(e2 < 0) { nums1[curr]=nums1[e1]; e1--; } else { if(nums1[e1]>nums2[e2]) { nums1[curr]=nums1[e1]; e1--; } else { nums1[curr]=nums2[e2]; e2--; } } curr--; } } }
Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,1,1], k = 2
Output: 2
Example 2:
Input: nums = [1,2,3], k = 3
Output: 2
class Solution {
public int subarraySum(int[] nums, int k) {
Map<Integer,Integer> hm = new HashMap<>(); int count =0; int sum =0; hm.put(0,1); for(int i =0; i<nums.length;i++){ sum = sum+nums[i]; if(hm.containsKey(sum-k)) { count= count+ hm.get(sum -k); } hm.put(sum, hm.getOrDefault(sum, 0)+1); } return count; } }