27.Remove Element
https://leetcode.com/problems/remove-element/
我用的方法是记录相同的个数,移动不同的元素,看Discuss,发现有人用记录不同个数来移动。
public class Solution {
public int removeElement(int[] nums, int val) {
int count = 0;
for(int i = 0; i < nums.length; i++)
{
if(nums[i] == val)
count++;
else
nums[i-count] = nums[i];
}
return nums.length - count;
}
}
283.Move Zeroes
https://leetcode.com/problems/move-zeroes/
这道题和上面27差不多。
public class Solution {
public void moveZeroes(int[] nums) {
int count = 0;
int len = nums.length;
for(int i =0 ; i < len; i++)
{
if(nums[i] == 0)
count++;
else
{
nums[i-count] = nums[i];
}
}
for(int i = len- count; i < len; i++)
nums[i] = 0;
}
}
28.Implement strStr()
https://leetcode.com/problems/implement-strstr/
当年最在行的莫过于字符串的遍历这种简单的题了,暴力解法,这次忘记考虑两个是否都是“”。
public class Solution {
public int strStr(String haystack, String needle) {
int lenH = haystack.length();
int lenN = needle.length();
for(int i = 0 ; i <= lenH - lenN; i++)
{
boolean flag = true;
for(int j = 0; j < lenN; j++)
{
if(haystack.charAt(i + j) != needle.charAt(j))
{
flag = false;
break;
}
}
if(flag)
return i;
}
if(lenH == lenN && lenH == 0)
return 0;
else
return -1;
}
}