面試10大演算法題匯總-字串和數組7,演算法數組
14.實現strStr():搜尋一個字串在另一個字串中的第一次出現的位置
例:
#include <stdio.h>#include <string.h>int main (){ char str[] ="This is a simple string"; char * pch; pch = strstr (str,"simple"); cout<<(*pch)<<endl; return 0;}
輸出:s
這裡主要要考慮一下特殊情況。
Code:
public class test {public static String strStr(String origin, String needle) {int originLen = origin.length();int needleLen = needle.length();if (needleLen == originLen && originLen == 0)return "";if (needleLen == 0)return origin;for (int i = 0; i < originLen; ++i) {if (originLen - i + 1 < needleLen)return null;int k = i;int j = 0;while (j < needleLen && k < originLen&& needle.charAt(j) == origin.charAt(i)) {++j;++k;if (j == needleLen)return origin.substring(i);}}return null;}public static void main(String[] args) {int[] a = { 2, 7, 11, 23 };}}
16.尋找插入位置:給定一個有序數組和一個目標值,若該值在數組中存在,則返回其index,否則返回其應該插入的位置。
例:
[1,3,5,6], 5 -> 2
[1,3,5,6], 2 -> 1
[1,3,5,6], 7 -> 4
[1,3,5,6], 0 -> 0
解法一:遍曆
Code:
public class test {public static int arrPos(int[] A, int target) {if (A == null)return 0;if (target <= A[0])return 0;for (int i = 0; i < A.length - 1; i++) {if (target > A[i] && target <= A[i + 1]) {return i + 1;}}return A.length;}public static void main(String[] args) {int[] a = { 2, 7, 11, 23 };System.out.println(arrPos(a, 223));}}
解法二:二分尋找
Code:
public class test {public static int arrPos(int[] A, int target) {if (A == null || A.length == 0)return 0;return searchInsert(A, target, 0, A.length - 1);}public static int searchInsert(int[] A, int target, int start, int end) {int mid = (start + end) / 2;if (target == A[mid])return mid;else if (target < A[mid])return start < mid ? searchInsert(A, target, start, mid - 1): start;elsereturn end > mid ? searchInsert(A, target, mid + 1, end): (end + 1);}public static void main(String[] args) {int[] a = { 2, 7, 11, 23 };System.out.println(arrPos(a, 223));}}