google codes only
1 two sum
class Solution {
public int[] twoSum(int[] nums, int target) {
int n= nums.length;
/*
HashMap<Integer,Integer> mpp = new HashMap();
for(int i=0;i<n;i++)
mpp.put(nums[i],i);
int [] ans = {-1,-1};
int low =0;
int high = n-1;
Arrays.sort(nums);
while(low < high)
{
int sum = nums[low] + nums[high];
if(sum==target)
{
ans[0] = mpp.get(nums[low]);
ans[1] = mpp.get(nums[high]);
break;
}
else if (sum < target)
low++;
else
high--;
}
return ans;
*/
HashMap<Integer,Integer> mpp = new HashMap();
int [] ans = new int[2];
ans[0]=ans[1] =-1;
for(int i=0;i<n;i++)
{
int moreNeeded = target - nums[i];
//check in maap already present moreneeded
if(mpp.containsKey(moreNeeded))
{
ans[0] = mpp.get(moreNeeded);
ans[1] = i;
break;
}
mpp.put(nums[i],i);
}
return ans;
}
// }
}
2.. Add two numbers in LinkedList
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode();
ListNode temp = dummy;
int carry =0;
while(l1 != null || l2!=null || carry==1)
{
int sum=0;
if(l1 != null)
{
sum+=l1.val;
l1=l1.next;
}
if(l2 != null)
{
sum+=l2.val;
l2=l2.next;
}
sum+=carry;
carry = sum/10;
ListNode node = new ListNode(sum%10);
temp.next =node;
temp = temp. next;
}
return dummy.next;
}
}
----------------------------------------------------------------------
dp
-----------
class Solution {
int [][]dp ;
boolean check (String s, int left, int right)
{
if(left >= right) // surpass the string
return true;
if(dp[left][right] != -1) return dp[left][right]==1;
if(s.charAt(left)==s.charAt(right) && check(s,left+1,right-1))
{
dp[left][right]= 1;
return true;
}
else
{
dp[left][right]=0;
return false;
}
}
public String longestPalindrome(String s) {
int n = s.length();
dp = new int[n][n];
for (int[] row : dp) {
Arrays.fill(row, -1); // Initialize dp array with -1
}
int start = 0, maxLen = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (check(s, i, j) && j - i + 1 > maxLen) {
start = i;
maxLen = j - i + 1;
}
}
}
return s.substring(start, start + maxLen);
}
}
Comments
Post a Comment