您的位置:首页 > 编程语言 > Java开发

【leetcode】Array——easy(java)

2016-12-07 16:27 363 查看

【26】Remove Duplicates from Sorted Array

题目

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,

Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.

给定一个排序数组,删除重复的位置,使每个元素只出现一次并返回新的长度(不要为另一个数组分配额外的空间,必须使用常量内存来做到这一点)。

思路

用两个变量作为下标向后移动,一个遍历数组,一个去掉重复元素(只存储没有重复的元素)。

代码

public class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length == 0 || nums.length == 1) {
return nums.length;
}
int size = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[size]) {
nums[++size] = nums[i];
}
}
return size + 1;
}
}


【27】Remove Element

题目

Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example:

Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

给定数组和值,原位删除该值的所有实例,并返回新长度(不要为另一个数组分配额外的空间,必须使用常量内存来做到这一点,可以更改元素顺序)。

思路

因为可以改变元素顺序,所以头尾交叉遍历。若头的值等于给定值,则将尾的值赋给头,同时尾向前移动;若不等于,则头向后移动。

代码

public class Solution {
public int removeElement(int[] nums,int val) {
int i = 0, tail = nums.length - 1;
while (i <= tail) {
if (nums[i] == val) {
nums[i] = nums[tail];
tail--;
} else {
i++;
}
}
return tail + 1;
}
}


【88】Merge Sorted Array

题目

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

给定两个排好序的数组nums1和nums2,将nums2汇入nums1成为一个排序数组。

思路

从数组nums1的尾巴(即下标为n+m-1处)向头开始赋值,大的放在后面。

代码

public class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
for (int i = m + n - 1; i >= 0; i--) {
if (n > 0 && m > 0) {
nums1[i] = nums1[m - 1] > nums2[n - 1] ? nums1[(m--) - 1] : nums2[(n--) - 1];
} else if (n == 0) {
nums1[i] = nums1[(m--) - 1];
} else {
nums1[i] = nums2[(n--) - 1];
}
}
}
}


【283】Move Zeroes

题目

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:

You must do this in-place without making a copy of the array.

Minimize the total number of operations.

把所有的0移到后面,非0数字的顺序保持不变(不能复制数组)。

思路

用两个下标,使得left总是指向第一个值为0的元素,right不断向后遍历,一旦right指向的元素值不为0(此时指向的必定是0后的第一个非0数),则将left和right指向的元素值交换,这时left向后移一位,继续指向第一个值为0的元素,right依旧向后寻找0后的第一个非0数。

代码

public class Solution {
public void moveZeroes(int[] nums) {
int n = nums.length, left = 0, right = 0, temp;
while (right < n) {
if (nums[right] != 0) {
temp = nums[right];
nums[right] = nums[left];
nums[left++] = temp;
}
right++;
}
}
}


【189】Rotate Array

题目

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:

Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

Hint:

Could you do it in-place with O(1) extra space?

旋转数组。

思路

n个元素的数组旋转k步,以下步骤可得:<1>翻转前n-k个元素;<2>翻转后k个元素;<3>翻转这n个元素。

代码

public class Solution {
public void rotate(int[] nums, int k) {
int n = nums.length;
if (n == 0) return ;
if (n < k) {
k = k % n;
}
reverse(nums, 0, n - k - 1);
reverse(nums, n - k, n - 1);
reverse(nums, 0, n - 1);
}
private int[] reverse(int[] nums, int begin, int end) {
while (begin < end) {
int temp = nums[begin];
nums[begin] = nums[end];
nums[end] = temp;
begin++;
end--;
}
return nums;
}
}


【66】Plus One

题目

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

思路

判断每一位(包括进位)是否等于9,如果不等于9则在该位加1即可返回;若等于9则往下标小的方向进位。对于最高位要单独处理,假如最高位等于9则要多一位表示。

代码

public class Solution {
public int[] plusOne(int[] digits) {
int i;
for (i = digits.length - 1; i >= 0 && digits[i] == 9; i--) {
digits[i] = 0;
}
if (i >= 0) {
digits[i] += 1;
return digits;
}
int[] ans = new int[digits.length + 1];
ans[0] = 1;
for (int j = 0; j < digits.length; j++) {
ans[j + 1] = digits[j];
}
return ans;
}
}


【118】Pascal’s Triangle

题目

Given numRows, generate the first numRows of Pascal’s triangle.

For example, given numRows = 5,

Return

[

[1],

[1,1],

[1,2,1],

[1,3,3,1],

[1,4,6,4,1]

]

根据给定行数构造杨辉三角。

思路

每一行的头尾都设置为1;每行的中间部分的值都等于上一行的该位置的值加上一行的该位置的前面一个位置的值之和,即a[i][j]=a[i-1][j]+a[i-1][j-1]。

代码

public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
if (numRows == 0) {
return ans;
}
List<Integer> L = new ArrayList();
L.add(0, 1);
ans.add(0, L);
for (int i = 1; i < numRows; i++) {
L = new ArrayList();
L.add(0, 1);
for (int j = 1; j < i; j++) {
L.add(j, ans.get(i - 1).get(j - 1) + ans.get(i - 1).get(j));
}
L.add(i, 1);
ans.add(i, L);
}
return ans;
}
}


【119】Pascal’s Triangle II

题目

Given an index k, return the kth row of the Pascal’s triangle.

For example, given k = 3,

Return [1,3,3,1].

Note:

Could you optimize your algorithm to use only O(k) extra space?

返回杨辉三角的某一行。

思路

与118
cda7
题类似,不同在于用两个List,一个用作计算,另一个用作存取。

代码

public class Solution {
public List<Integer> getRow (int rowIndex) {
List<Integer> ans = new ArrayList<>();
List<Integer> cpt = new ArrayList<>();
if (rowIndex == 0) {
ans.add(1);
return ans;
}
cpt.add(1);
cpt.add(1);
ans = cpt;
for (int i = 2; i <= rowIndex; i++) {
cpt = new ArrayList();
cpt.add(1);
for (int j = 1; j < i; j++) {
cpt.add(j, ans.get(j - 1) + ans.get(j));
}
cpt.add(1);
ans = cpt;
}
return ans;
}
}


【217】Contains Duplicate

题目

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

给定数组,判断是否有重复的。

思路

用HashSet,因为Set只能存不重复的值,所以如果没有存进去则表示有重复的。

代码

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


【219】Contains Duplicate II

题目

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.

给定数组和整数k,判断是否能在数组里找到值相同的两个元素,且这两个元素距离在k以内(包括k)。

思路

用HashMap。按序遍历,如果在HashMap上找到此时的值,则计算两个元素的距离,假如符合则返回true,假如不符合则给该值赋上新位置;如果在HashMap上找不到此时的值,则把该值和该位置存入HashMap中。

代码

public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
if (i - map.get(nums[i]) <= k) {
return true;
}
}
map.put(nums[i], i);
}
return false;
}
}


【1】Two Sum

题目

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

给定一个整数数组,返回两个数字的索引使得它们相加到一个特定的目标,假设每个输入都有一个解决方案。

思路

用hash。每次在hash里面找是否存在此刻遍历(第i个位置)的值,若不存在,则把该值所对应的第二个加数存入hash的第i个位置;若存在,此时可返回。

代码

public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.get(nums[i]) != null) {
int[] ans = {map.get(nums[i]), i};
return ans;
} else {
map.put(target - nums[i], i);
}
}
int[] ans = {};
return ans;
}
}


【169】Majority Element

题目

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

给定数组,找到一个出现过超过⌊ n/2 ⌋次的元素。

思路

因为要找的元素出现超过⌊ n/2 ⌋次,所以该元素出现的次数肯定大于其他所有元素出现的次数。先假设一个元素为maj,并用count计算maj出现几次,向后遍历,若接下来出现的值等于maj,则count++;若不等于,则count- -。一旦count的值减少为0,则改变maj为新值。如此循环。

代码

public class Solution {
public int majorityElement(int[] nums) {
int count = 1, maj = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] == maj) {
count++;
} else {
count--;
}
if (count == 0) {
maj = nums[i];
count++;
}
}
return maj;
}
}


【414】Third Maximum Number

题目

Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

Example 1:

Input: [3, 2, 1]

Output: 1

Explanation: The third maximum is 1.

Example 2:

Input: [1, 2]

Output: 2

Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

Example 3:

Input: [2, 2, 3, 1]

Output: 1

Explanation: Note that the third maximum here means the third maximum distinct number.

Both numbers with value 2 are both considered as second maximum.

给定数组,若数组中存在第三大的值,则返回第三大的值;否则返回最大的值。

思路

用n来计算数组里有多少个数(除了重复的元素以及Integer.MIN_VALUE),t则是判断数组里是否存在Integer.MIN_VALUE。再根据n和t判断是要输出最大值还是第三大值。

代码

public class Solution {
public int thirdMax(int[] nums) {
int max = Integer.MIN_VALUE, second = Integer.MIN_VALUE, third = Integer.MIN_VALUE, t = 0, n = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == Integer.MIN_VALUE) {
t = 1;
}
if (nums[i] > max) {
third = second;
second = max;
max = nums[i];
n++;
} else if (nums[i] < max && nums[i] > second) {
third = second;
second = nums[i];
n++;
} else if (nums[i] < second && nums[i] > third) {
third = nums[i];
n++;
}
}
if (n < 2 || (n == 2 && t == 0)) {
return max;
} else {
return third;
}
}
}


【121】Best Time to Buy and Sell Stock

题目

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

Input: [7, 1, 5, 3, 6, 4]

Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]

Output: 0

In this case, no transaction is done, i.e. max profit = 0.

找出买卖股票的最大利润。

思路

遍历数组,当遍历到第i个数组时,min为前i-1个数的最小值,则prices[i]-min为第i天卖出的最大利润,同时用profit记录第i天前(包括第i天)卖出的最大利润的最大值。

代码

public class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int profit = 0, min = prices[0];
for (int i = 1; i < prices.length; i++) {
min = min < prices[i - 1] ? min : prices[i - 1];
profit = (prices[i] - min) < profit ? profit : (prices[i] - min);
}
return profit;
}
}


【448】Find All Numbers Disappeared in an Array

题目

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

Input:

[4,3,2,7,8,2,3,1]

Output:

[5,6]

如果数组有n个元素,则返回1到n中不等于数组中元素值的数。

思路

把数组中出现的数当成位置,数组中该位置上的值置为负值,然后重新遍历如果大于0,则表示从未出现过。

代码

public class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> ans = new ArrayList<>();
int n = nums.length, temp;
if (n == 0) {
return ans;
}
for (int i = 0; i < n; i++) {
nums[Math.abs(nums[i]) - 1] = - Math.abs(nums[Math.abs(nums[i]) - 1]);
}
for (int i = 0; i < n; i++) {
if (nums[i] > 0) {
ans.add(i + 1);
}
}
return ans;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: