package ygy.test.week4;
/**
* Created by guoyao on 2017/9/23.
*/publicclassImplementstrStr {publicstaticvoidmain(String[] args) {
System.out.println(strStr("a","a"));
}
/**
* Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
* 大串包小串
*/publicstaticintstrStr(String haystack, String needle) {
if (needle.length() == 0) {
return0 ;
}
for(int i = 0 ; i < (haystack.length() - needle.length() + 1) ;i ++) {
if (haystack.substring(i, needle.length() + i).equals(needle)) {
return i;
}
}
return -1 ;
}
}
Maximum Subarray
package ygy.test.week4;
/**
* Created by guoyao on 2017/9/24.
*/publicclassMaximumSubarray {publicstaticvoidmain(String[] args) {
System.out.println(maxSubArray(newint[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}));
System.out.println(maxSubArray_2(newint[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}));
}
//{ -1 , -2 , 3 , -4 , 9 , 2,24 ,-12}publicstaticintmaxSubArray(int[] nums) {
int sum=0;
int lastSum=Integer.MIN_VALUE;
for (int i=0; i < nums.length; i++) {
if (sum < 0) {
sum=nums[i];
} else {
sum+=nums[i];
}
if (sum > lastSum) {
lastSum=sum;
}
}
return lastSum;
}
//leetcodepublicstaticintmaxSubArray_2(int[] nums) {
int subNum=nums[0];
int maxNum=nums[0];
for (int i=1; i < nums.length; i++) {
subNum=Math.max(subNum + nums[i], nums[i]);
maxNum=Math.max(maxNum, subNum);
}
return maxNum;
}
}
Search Insert Position
package ygy.test.week4;
/**
* Created by guoyao on 2017/9/23.
*/publicclassSearchInsertPosition {publicstaticvoidmain(String[] args) {
int[] nums={1, 2, 3, 4, 56, 467};
System.out.println(searchInsert(nums, 5));
}
/**
*Given a sorted array and a target value, return the index if the target is found.
* If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
*/publicstaticintsearchInsert(int[] nums, int target) {
if (nums.length == 0) {
return0;
}
if (nums.length == 1 && target < nums[0]) {
return0;
}
int start = 0 , end = nums.length -1 ;
int mid=(start + end) >> 1;
while (start <= end) {
if (nums[mid] > target) {
end=mid - 1;
} elseif (nums[mid] < target) {
start=mid + 1;
} else {
return mid ;
}
mid = (start + end ) >> 1 ;
}
return mid + 1 ;
}
}